BUG
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.
It contains a single element.
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.
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.
Closing in favor of https://github.com/cypress-io/cypress-documentation/issues/306
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
Most helpful comment
You could probably just do...
cy.get('div:contains(bar)')