How do I check there are multiple elements that contain something? - Cypress

Viewed 6460

I am trying to check that a list contains 2 specific entries using Cypress.

I have tried:

cy.get('ul.messages_list')
            .children()
            .contains('text')
            .and('contain', 'emailAddress)
            .should('have.length', 2)

The problem is that once I use .contains() it is in a single element and I cannot check that there are multiple of them.

3 Answers

Try to replace .contains('text') with .should('contain', 'text').

This way you should be able to chain assertions with .and():

cy.get('ul.messages_list')
  .children()
  .should('contain', 'text')
  .and('contain', 'emailAddress)
  .and('have.length', 2)

I just had the same problem. Would this work for you?

cy.get('ul.messages_list').children().should(($children) => {
            expect($children).to.contain('text');
            expect($children).to.contain('emailaddress);
            expect($children.length).to.eq(2);
        })

I'm a total Cypress noob of about 8 hours eperience so you might have to do some tweaking :-)

const messages = cy.get('ul.messages_list').children();

messages.contains('text');
messages.contains('emailAddress');

messages.should('have.length', 2);

Related