How to check if an element contains multiple items in Cypress.io
Asked Answered
L

4

35

How can I check if an element contains multiple items in Cypress.io without replicating my code so much?

Current Example:

cy.get(".column")
  .children()
  .contains("Name");

cy.get(".column")
  .children()
  .contains("Age");

cy.get(".column")
  .children()
  .contains("Weight");

cy.get(".column")
  .children()
  .contains("Height");

cy.get(".column")
  .children()
  .contains("Favorite Color");
Liaotung answered 11/7, 2019 at 18:20 Comment(0)
S
61

You can do it in this way:

cy.get('.column')
  .children()
  .should('contain', 'Name')
  .and('contain', 'Age')
  .and('contain', 'Weight')
  .and('contain', 'Height')
  .and('contain', 'Favorite Color')
Satan answered 11/7, 2019 at 19:3 Comment(3)
Perfect! Thank you for your help!!Liaotung
That works, but it could yield false positives if the data happens to be 'Age' for example.Allcot
@DanDascalescu Yes, indeed. You could use the .contains method instead and pass a selector like so: .contains('.my-item', 'Age').Prescriptive
C
7

Sometimes you can do it in this way:

     const column = ['Name', 'Age', 'Weight', 'Height']

        column.forEach(function (value) {
            cy.get('.column')
              .children()
              .should('contain', value)
        })
Carolacarolan answered 26/8, 2021 at 20:32 Comment(0)
U
0

I'm not saying this is better (in fact it's kind of procedural) but it might be instructive/useful:

const strings=["Name","Age","Weight","Height","Favorite Color"];

cy.get('.column').within(() => {
  for (const string of strings) {
    cy.contains(string);
  }  
})
Universe answered 19/4 at 18:28 Comment(0)
Y
-1

I ended up using a regex like so:

function assertContainsMultiple(...msgs) {
  const containsRegex = new RegExp(msgs.join('.+'))
  cy.get('#msg').contains(containsRegex)
}

Partial credit to Github co-pilot--I had the idea, typed "const containsRegex" and it knew what I wanted. Nice.

Yucca answered 9/8, 2023 at 22:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.