Reputation: 911
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");
Upvotes: 36
Views: 38449
Reputation: 1
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);
}
})
Upvotes: 0
Reputation: 4293
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.
Upvotes: -1
Reputation: 71
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)
})
Upvotes: 7
Reputation: 8652
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')
Upvotes: 62