Marvel
Marvel

Reputation: 3

Cypress's get stops at first occurence

When I run my test against that HTML code

<body>
  <div tester='notmatching'>
    foo
  </div>
  <div tester='matching'>
    bar
  </div>
</body>

</html>

Cypress doesn't look beyond the first "div".

Here is my test :

context('Home', () => {
  beforeEach(() => {
    cy.visit('http://example.org')
  })
  it('Find a div', () => {
    cy.get('div').should('have.attr', 'tester', 'matching')
  })
})

Si I get the following error :

CypressError: Timed out retrying: expected '[ <div>, 1 more... ]' to have attribute 'tester' with the value 'matching', but the value was 'notmatching'

So when I put the line :

cy.get('div').should('have.attr', 'tester', 'notmatching')

It works.

What am I doing wrong ?

Upvotes: 0

Views: 357

Answers (1)

jsdeveloper
jsdeveloper

Reputation: 4045

I think you have to target the second matching element using eq:

cy.get('div').eq(1).should('have.attr', 'tester', 'matching')

https://docs.cypress.io/api/commands/eq.html#Syntax

EDIT:

If you want to iterate through them and check each one, you could do this:

cy
  .get('div')
  .each(($el, index, $list) => {
    if ($el.attr('tester') === 'matching') {
      // do something here

EDIT 2:

If you just want to match the div with that attribute - you can do this:

cy.get("div[tester='matching']").should(...

Upvotes: 1

Related Questions