What methods can Cypress use to validate content containing hyperlinks?

My current task is to develop an automation test that confirms the presence/display of content containing a hyperlink embedded within text. Please refer to the screenshot I have provided for better understanding, as it illustrates the specific content enclosed in the red box. Additionally, I have highlighted the relevant code using Google DevTool.

https://i.stack.imgur.com/XcfRS.png

Answer №1

If you're looking to locate an "a" element within your "li" element, you can verify its href attribute and text content.

cy.get(selector)
    .find("a")
    .should("have.attr", "href", "/path")
    .should("have.text", "Alcohol Anonymous");

Answer №2

Make sure to take a look at this insightful blog post by the team at Cypress. They provide a comprehensive guide on the various methods for testing links using Cypress

For more detailed information, be sure to scroll down to the Checking every link section which I believe will address your needs

Answer №3

Verifying this scenario with just a few lines of code is simple:

Code Example

   cy.contains("a","Alcohol Anonymous").invoke('attr','href')
     .should('include','/ attr value')
   cy.contains("li", "text").should('be.visible)

Answer №4

If you wish to verify the exact texts, you can create an array like this:

const texts = [
  'Alcohol Anonymous',
  'Cance Research',
  'Cancer Trust',
  'Drinkware',
] //Add additional texts

cy.get('a').each(($ele, index) => {
  cy.wrap($ele).should('have.text', texts[index])
})

Alternatively, if you only want to ensure that all links have some text, you can use:

cy.get('a').each(($ele, index) => {
  cy.wrap($ele).invoke('text').should('not.be.empty')
})

To check both content and the hyperlink simultaneously, you can try something like this:

const texts = [
  'Alcohol Anonymous',
  'Cance Research',
  'Cancer Trust',
  'Drinkware',
] //Add extra texts
const links = [
  'https://example1.com',
  'https://example2.com',
  'https://example3.com',
  'https://example4.com',
] //Add more links

cy.get('a').each(($ele, index) => {
  cy.wrap($ele)
    .should('have.text', texts[index])
    .and('have.attr', 'href', links[index])
})

Or, if you simply want to confirm that both the content and hyperlinks are present, you can use:

cy.get('a').each(($ele, index) => {
  cy.wrap($ele).invoke('text').should('not.be.empty')
  cy.wrap($ele).invoke('attr', 'href').should('not.be.empty')
})

Answer №5

@GustavoCesário is absolutely right, it is essential to target the specific section of the page that contains the links.

If you simply use cy.get('a'), you will capture elements like the logo and navigation menu, which are not relevant for your testing purposes.

Additionally, when looking for full text, remember to use <li> instead of <a>.

const expectedParagraphs = [
  'Alcohol Anonymous is a free support group that offers help for anyone choosing to stop drinking.',
  'Cancer Research provides information on how alcohol affects your risk of the disease.',
  'Carers Trust gives help to people who are affected by someone else’s drinking.',
  ...
]

beforeEach(() => {
  cy.visit('https://www.drinkiq.com/en-gb/get-help/');
})

it('verifies the content of each list item', () => {

  cy.get('main')
    .find('li')
    .each(($li, i) => {
      const paragraph = $li.text()
      expect(paragraph).to.eq(expectedParagraphs[i])
    })
})

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Identifying errors in a React component upon loading

As I delve into my project, my main focus lies on detecting errors within a component. The ultimate goal is to seamlessly redirect to the home page upon error detection or display an alternate page for redirection. I am seeking a programmatic solution to ...

The new mui v5 Dialog is having trouble accepting custom styled widths

I am facing an issue with my MUI v5 dialog where I cannot seem to set its width using the style() component. import { Dialog, DialogContent, DialogTitle, Paper, Typography, } from "@mui/material"; import { Close } from "@mui/icons- ...

Retrieve identical values from an array and display them using Vue.js

I am working with a product array that includes id, name, and category data for 5 products. For example, let's say there are 3 products assigned to the mobile category and 2 products assigned to the computer category. What is the best approach to rend ...

Creating a Node.js application using Express requires careful consideration of file structure and communication methods

Struggling to pass login form credentials to existing JavaScript files for logic and info retrieval. Login page contains a form with POST method. main.js handles the login: main.js module.exports = { returnSessionToken: function(success, error) { ...

My function is named, however, the output is recorded prior to the function completing its execution

I've implemented a function named createUser, designed to save user data in the database. If successful, it should return true; otherwise, false. The code for this function is as follows: exports.createUser = (user) => { const salt = crypto.rando ...

Issue with IntelliJ: TypeScript Reference Paths Are Not Relative

I am currently using IntelliJ as my IDE, but I am facing an issue with configuring gulp-typescript to compile my typescript code. The problem arises from the fact that IntelliJ does not treat my reference paths relatively, instead it references them from m ...

Combine multiple arrays in JavaScript into a single array

Here is the array I am working with: array = ['bla', ['ble', 'bli'], 'blo', ['blu']] I need to transform it into this format: array = ['bla', 'ble', 'bli', 'blo', &a ...

Using ngFor in Angular 6 to create a table with rowspan functionality

Check out this functional code snippet Desire for the table layout: <table class="table table-bordered "> <thead> <tr id="first"> <th id="table-header"> <font color="white">No.</font> </th> <th id="table-hea ...

Working with JSON in AJAX with Javascript and C# to handle array data

When attempting to send an array via AJAX using JSON, I am encountering a problem where my C# handler is unable to properly handle the query. It seems that the querystrings are merging together inexplicably. In the scenario presented here, I am trying to ...

Pass information from Vue JS v-for to a button when it is clicked

Just started learning Vue JS and encountered a small issue I'm currently looping through an array with a button inside the div I'm iterating over The goal is to grab the data of the selected item after clicking on the button For example, suppo ...

Creating Apache Arrow vectors in TypeScript for writing data to a Table

Currently, I am in the process of creating a method that is designed to take a column of data, referred to as data: any[], and then pack it into an Arrow-typed Array Buffer for insertion into an Arrow table. To illustrate with an example, if we consider T ...

A guide on retrieving the upload status of a file using an AJAX post request

Is there a way to retrieve the status of uploaded files when the user cancels the process while uploading multiple files using an ajax call? This is how I am currently making the ajax request to upload files: var request = $.ajax({ url: 'file ...

How to Refresh EJS Template in an Express Node.js Application

Currently, I am integrating discord.js with express and facing a challenge. I want my webpage to automatically update whenever the client.on("message") event is triggered. According to my knowledge and research, it seems that rendering an ejs template is o ...

Toggle Vue transitions on and off with a boolean parameter

Is there a way to dynamically disable a transition animation in Vue based on a boolean value? Currently, the animation is enabled with the following code: <transition name="fadeUp"> <div v-if="elIsVisible"> <p>Foo Bar</p> ...

Having Trouble Importing a Dependency in TypeScript

My experience with using node js and typescript is limited. I attempted to include the Paytm dependency by executing the following code: npm install paytmchecksum or by inserting the following code in package.json "dependencies": { ... & ...

Next.js customization script

How can I efficiently create a class toggle function for a slide-in menu in Next.js? I've developed a menu with a sliding functionality that toggles when a button with the class "toggled" is clicked. However, I'm unsure if this approach aligns w ...

Generate a collection of information by gathering metadata from Xray

I've been struggling to populate an array with metadata retrieved using Xray. The issue arises when the function is called by an API endpoint on my server to fetch links from my application. My main challenge seems to be related to promises, as there ...

What is the best way to test speedy AJAX response times using Webdriver.io?

Currently, I am creating Cucumber.js tests using Webdriver.io. Everything seems to be going smoothly, but I'm encountering an issue with the mock server responding too quickly with AJAX. The "Loading..." message is not visible because the content load ...

Discover the best way to sort products by category

I'm in the process of developing an online store where customers can choose from three options: "body lotion," "body wash," and "body scrub." Once a selection is made, the corresponding product will be displayed. The products are stored in an array n ...

Utilizing JavaScript for enhancing the appearance of code within a pre element

Is there a way to dynamically highlight the code inside a pre element using vanilla JavaScript instead of JQuery? I'm looking for a solution that colors each tag-open and tag-close differently, displays tag values in another color, and attributes with ...