Cypress: .contains() only yields first match

Created on 5 Dec 2017  路  6Comments  路  Source: cypress-io/cypress

  • Operating System: Mac 10.12.6
  • Cypress Version: 1.1.2
  • Browser Version: Chrome 62.0.3202.94

Is this a Feature or Bug?

BUG

How to reproduce:

In a page with multiple spans containing the text "Test", issue the following:

cy.contains("Test").then((results) => {
  debugger
})

When the dev tools stops at the debugger line, inspect results.

Current behavior:

It contains a single element.

Desired behavior:

Documentation here:
https://docs.cypress.io/api/commands/contains.html#Content

states:
.contains() yields the new DOM element(s) it found.

It seems it only yields a single element, but should yield them all.

documentation

Most helpful comment

You could probably just do... cy.get('div:contains(bar)')

All 6 comments

This is in fact an error with the documentation. .contains() always yields the first element containing the text (also with regard taken to find relevant elements over deepest). The yields statement should be updated to:

.contains() yields the new DOM element it found.

If you have a particular use case for having a command in Cypress that yields multiple elements with the containing text, please specify an example and your need so that we can consider adding it as a new feature.

All of the rest of the contains documentation states everywhere that it yields the first element. I guess you pointed out the one place where it conflicts with that. It's because those sections are reusable templates.

Thanks for correcting the doc. Didn't see this mentioned elsewhere - when trying to figure out what the promise yields, the Yields section is where I looked.

My use case is to click through items on a list deleting any previous test entries, which are identifiable by a match on a text pattern. I have now implemented this by getting all items with a cy.get() and then iterating through them with .each() and testing their text with

if ($li.text().match(/MyPattern/)) doStuff()

Not quite as concise as a .contains() but does the trick.

You could probably just do... cy.get('div:contains(bar)')

I can still see that the docs say yield firs element
image

Was this page helpful?
0 / 5 - 0 ratings