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

Is there a way to retrieve an attribute from a nested object in a loop while using VueJS?

Currently, I am facing an issue while trying to access a property within a nested object using a loop in my vuejs project. It's strange because similar nested objects work fine except for one. <template> <div> <tr v-for=" ...

The strange behavior of !important, display:none, and .height()

While working with a piece of JS code yesterday, I stumbled upon something peculiar. There was a div element that was initially hidden using display:none, and I was utilizing its height in some JavaScript calculations. Everything was functioning properly u ...

Adding a picture to the webpage and saving it temporarily on the site

After exploring all options on the site, testing it rigorously and closely following the instructions provided, I am still unable to determine where exactly I went wrong. Website Link: The main goal is to upload an image and temporarily store it within t ...

Automatically deliver a message regularly at set intervals on Discord across all groups and guilds

Currently, I am developing an event-bot to use in multiple Discord groups. Here is the code snippet I have been working on: if (command === "init") { message.channel.send("BunnBot starting..."); var interval = setInterval (function () { me ...

What is the best way to transfer parameters from the Vue root to a component?

Currently, I am attempting to transfer a string value from index.cshtml to the main Vue element. The specific parameter I want to pass is: userId Location: Index.cshtml (this is where the parameter is obtained) @using Microsoft.AspNetCore.Identity @inje ...

What is the best way to integrate a new unique identifier into an existing MongoDB document using NodeJS?

I am looking to add up a field in a document when I input a new entry that has a replicated unique id. This is the code I have so far: MongoClient.connect(process.env.MONGODB_URI || process.env.DB_CONNECTION, { useUnifiedTopology: true, useNewUrlParser ...

a guide on retrieving FormData objects in PHP

Hey everyone, I have a question regarding a sample code snippet I posted here. In this code, I am successfully uploading a file using Ajax JQuery. However, I am struggling to figure out how to read the content of the uploaded file in my PHP code. Can anyon ...

Customize CSS to target the first and last elements in a row using flexbox styling

I am facing a challenge in selecting the last element of the first row and the first element of the last row within a flex container. The setup involves a flex-wrap: wrap; for my flex container where all elements have flex: auto; with different sizes. Thi ...

Safari is unable to display the button text, while Chrome has no problem showing it

In Safari, the text of the button is not showing up properly. I am able to retrieve the text using jQuery in the console though. However, there seems to be an issue with recognizing the click event. <div class="btn-group btn-group-lg"> <button ...

Executing actions on events in a Basic jQuery sliderLearn how to handle events and execute

I utilized the slider from the bjqs plugin at after reviewing the documentation, I noticed it only offers options and lacks events/functions. I am referring to events/functions like onSlideChange and onSlideDisplay. While other plugins such as bxslid ...

What is the best way to include a second (concealed) value in a cell using datatables

Query: How can I send specific cell values to a controller using POST method, where one value is visible and the other is hidden? For instance, each cell contains both Time and Date data but only the Time is displayed in the datatable. I need to post both ...

Send dropdown selections to a Javascript function and convert them into an array

Within my JavaScript function, I need to pass multiple selected values from dropdown menus and store them in a JavaScript array. Each time a value is selected and sent using the onchange() function, it should be added to the array. If the same value is sel ...

Running JavaScript within Electron is a straightforward process

Looking to create an Electron application that can take code entered into a text area, execute it, and display the result. Any advice on converting the text to JavaScript and running it? ...

The page is not able to be uploaded successfully, receiving a HTTP 200 status

Currently, my application is running in Express and I have a button that sends a POST request to the server. After receiving a 200 OK response, the HTML page is displayed. The issue I am facing is that even though I can see the HTML payload in Firebug, my ...

Plugin for Vegas Slideshow - Is there a way to postpone the beginning of the slideshow?

Is there a way to delay the start of a slideshow in JavaScript while keeping the initial background image visible for a set amount of time? I believe I can achieve this by using the setTimeout method, but I'm struggling to implement it correctly. Be ...

Is it possible to use ng-src to point to a file stored locally?

I am currently experimenting with using ng-src to load images from a local folder, but I keep encountering 404 errors. Can ng-src actually reference a local folder, or do you always have to use a hardcoded path like http://example.com/imgs/{{work.img}}.jpg ...

What is the best way to display only a specific container from a page within an IFRAME?

Taking the example into consideration: Imagine a scenario where you have a webpage containing numerous DIVs. Now, the goal is to render a single DIV and its child DIVs within an IFrame. Upon rendering the following code, you'll notice a black box ag ...

Steps for breaking down a given string into divisions that correspond to an A4 sheet

Within my content, there are various styles applied. For example: This is a <b>bolded</b> word. I am seeking a solution to divide this long string into smaller sections that would fit on an A4 page accurately. The goal is to maintain the integ ...

Grouping object properties in a new array using Java Script

I'm currently learning Java script and attempting to merge an Array of objects based on certain properties of those objects. For instance, I have the following array which consists of objects with properties a, b, c, pet, and age. I aim to create a n ...

Sharing data between the main component and the sidebar in React-Router

Currently working with Meteor in combination with React-Router, and this is the code I'm dealing with: Routes.jsx: Meteor.startup(() => { render( <Router history={browserHistory}> <Route path='/' component={App}> ...