Is there a way to verify if the content shown for each child is distinct from the others?

it('features', () => {
      home.featuresMainTitle("What you'll learn")
      cy.get('.grid').children().each(($el, index, $list) =>{
        const currentText = $el.find('h3').text()
        const nextText = $el.next().find('h3').text()
        expect(currentText).to.not.equal(nextText)
      })

I'm extracting a grid element from the DOM and verifying that the text of each child within the grid is different from the others.

The code functions as expected, but I feel there may be a more elegant solution to achieve the same result without using additional JavaScript variables (currentText and nextText). Perhaps there is a feature in Cypress that could streamline these lines of code and make it cleaner at first glance.

Answer №1

While the code may not be shorter, it does provide a more robust test:

By utilizing a Set, you can validate the lengths of .children() and the length of the set.

A Set object allows for storing unique values of any type

This method enables comparison across all children rather than just between next and current elements.

cy.get(".grid").children()
  .then($els => {
    const setOfTexts = new Set();
    [...$els].forEach(el => setOfTexts.add(el.innerText)); // stores only unique values
    return setOfTexts;
  })
  .then(setOfTexts => {
     cy.get(".grid").children().its('length')
       .should('eq', setOfTexts.size)
  })

Alternatively, with a reducer function:

cy.get(".grid").children()
  .then($els => [...$els].reduce((acc, el) => {
    acc.add(el.innerText)
  }, new Set()))
  .then(setOfTexts => {
     cy.get(".grid").children().its('length')
       .should('eq', setOfTexts.size)
  })

Answer №2

To enhance the process of counting unique values, consider implementing the Lodash uniqBy() method

cy.get('.grid')
  .children()
  .should($els => {
    const unique = Cypress._.uniqBy($els, (el) => el.innerText)
    expect(unique.length).to.eq($els.length)
  })

If all texts in the grid are distinct, this test will pass successfully.


Taking into account the <h3>

Assuming you are using a .find() within the .each() function, the same logic should apply unless there are specific <h3> elements in the grid that need to be excluded.

cy.get('.grid')
  .find('h3')
  .should($els => {
    const unique = Cypress._.uniqBy($els, (el) => el.innerText)
    expect(unique.length).to.eq($els.length)
  })

Answer №3

If you want to approach it differently, one way is to gather all the child elements, extract their text content, convert it into an array of unique values, and then compare it with the original array.

cy.get(".grid")
  .children()
  // retrieve innerText of each child element
  .then(($el) => Cypress._.map($el, (el) => el.innerText))
  .then((childrenText) => {
    // create new array with unique values only
    const uniqueText = Array.from(new Set(childrenText));
    expect(childrenText).to.deep.equal(uniqueText);
  })

Check out this example for a demonstration.

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

Store fresh JSON information in a newly created JSON document

As someone new to JavaScript, I really appreciate your assistance. I'm utilizing the randomuser.me API to generate a list of users, but the names are all in lowercase. With the help of someone else, I managed to capitalize the names using a script. N ...

Gather information from users using Node.js and integrate it with Stripe

As I am new to Node.js, my goal is to utilize nodejs & Stripe to gather user data such as name, phone number, email, city, etc. This way, I can easily identify the user from the Stripe dashboard along with all their corresponding information. on the server ...

Separate text by the number of letters in each word while ensuring that words are not split in half

I have created a function that splits a given article by a specified letter count, but it also separates words at the end of lines. I want to add a hyphen at the end of those lines if a word is incomplete. let textContent = `Lorem Ipsum is simply dummy tex ...

What is the best way to add portfolio projects into a React application?

I am currently building a portfolio using react. I am having trouble navigating to my projects through localhost:3000. The projects are stored in my includes folder and are not created with react, so it is different from using XAMPP as my server. My file ...

Adding a personalized service into a separate service within Angular 2

I am having trouble injecting my own service into another service. While I can inject standard Angular services like Http without any issues, attempting to inject custom services results in an exception. For example, here is how MyService is set up: impo ...

Guide to utilizing exact matching functionality in ExpressJs router

In my ExpressJs application, I have defined two routes like so: router.get("/task/", Controller.retrieveAll); router.get("/task/seed/", Controller.seed); When I make a request to /task/seed/, the Controller.retrieveAll function is call ...

The initial res.body object in NodeJS is enclosed in quotation marks

I've hit a roadblock while working on my social media website project using the MERN stack. Despite scouring the internet, I haven't been able to find a solution to the issue at hand. While following an online course, I encountered a problem tha ...

Instructions on setting up a custom HTTPS server using the Alexa ask-cli

I am facing an issue with deploying my Alexa skill using the alexa-cli tool (https://www.npmjs.com/package/ask-cli). Whenever I try to deploy my skill with an https server, I encounter the following error: ◞ Creating new skill...Call create-skill err ...

A more effective method for restricting the properties of a field in an aggregate query

In my MongoDB query, I am attempting to use the aggregate function to fetch data from one collection while limiting the amount of data retrieved from another collection. Here is the code snippet that I have come up with: getFamilyStats: function (req, res ...

Looking to place a global filter outside the primeNG table component?

I am currently utilizing primeNG in my project and I have a need to incorporate a global filter. The challenge I am facing is that I must add this filter in a different component. These two components are deeply nested within other components. My approach ...

What is the best way to style HTML content with MathJax following its retrieval with jQuery.load?

I recently encountered an issue while using jQuery.load to load a new page. The content on the original page is being treated strangely in some way. Specifically, I have code on the original page that formats LaTeX commands with MathJax: <script type=" ...

Guide for displaying d3.js chart using a vue.js method and specifying the target div

I'm working on my Vue code and here's a snippet of what I have: new Vue({ el : '#friendlist', data : { friends : [] }, methods : { fetchStats : function(){ const axios_data = { ...

Manipulate the contents of children divs within a parent div using JavaScript or JQuery

<div id="abc"> <div id="a_b"> abcd </div> <div id="c_d"> xyz </div> </div> I have a challenge where the divs on my page are generated dynamically and their IDs change every time the page loads. When the window i ...

What is the best way to trigger a function in the parent component using an event from the child component?

I'm currently immersed in learning React and am tackling the challenge of creating a game where the cards shuffle with each attempt. The card array and shuffle function are located in a parent component (using map to display the cards), while the retr ...

I prefer to avoid using the "#" sign in URLs

<a href="#" onClick="load_page()">intro</a> I am trying to avoid displaying the # sign in the URL, and I would like it to appear like this instead: www.mydomain.com/ However, it currently displays as follows: www.mydomain.com/# Is there a ...

Using this functionality on a ReactJS Functional Component

Hey everyone, I'm fairly new to using React and I'm currently trying to wrap my head around some concepts. After doing some research online, I stumbled upon a situation where I am unsure if I can achieve what I need. I have a functional componen ...

The ReactJS code encountered an error when attempting to access the 'location' property of an undefined or null reference

My Reactapp is encountering an error due to a specific file. import React from 'react'; import { Router, Route } from 'react-router'; import App from './components/App'; import About from './components/About'; im ...

simulate the act of clicking on a download link by utilizing a secondary click

adown is a link that allows users to download a file from my webpage. It functions properly on the page. However, btndown is a button designed to simulate clicking on the adown link, but unfortunately, it does not work as expected. When the btndown button ...

Methods for establishing state within a React Native render function

I encountered an issue when attempting to set state within the render lifecycle. Warning: It is not recommended to update state during an ongoing state transition, such as in the render method or another component's constructor. The render method s ...

Aggregating documents in MongoDB based on specific criteria shared by all members of the group

I'm currently working with a set of example documents structured like this: /* 1 */ { "_id" : ObjectId("61c50482f176d72cb660baa3"), "answer" : "yes",... /* 2 */ { "_id" : ObjectId(&quo ...