Testing two elements with the same text

Viewed 67

I have a page with two element containing the "some text", but cannot confirm it in my test.

Simplest example is this:

<div>some text</div>
<div>some text</div>
const selector = 'div'
const text = 'some text'

cy.get(selector)
  .contains(text)
  .should('have.length', 2);

Cypress log

expected to have a length of 2 but got 1

2 Answers

Unfortunately .contains() only ever returns one element. If multiple are found, the first one is returned.

You can instead add :contains() into the selector.

Since the selector and text are variables, a string template can build the final selector.

cy.get(`${selector}:contains(${text})`)
  .should('have.length', 2);

or put it in a .filter()

cy.get(selector)
  .filter(`:contains(${text})`)
  .should('have.length', 2);

You can also do something like this, using eq:

const selector = 'div'
const text = 'some text'
cy.contains(selector, text).eq(0).should('be.visible')
cy.contains(selector, text).eq(1).should('be.visible')
Related