I am having trouble finding documentation that explains how Cypress assertions work when cy.get()
matches multiple elements. For example:
Markup:
<div>
<button>one</button>
<button class='green'>two</button>
<button disabled>three</button>
</div>
Test:
cy.get('button').should('be.disabled');
Does Cypress assert that:
- the first matched element passes?
- all matched elements pass?
- at least one of the elements pass?
From experience I am guessing it is option 3 but I haven’t been able to find this explicitly addressed in the documentation.
Whereas
cy.get('button').click();
clicks… only the first button? All of them?
On the assertions, I’m afraid we are unintentionally writing tests that pass in cases where our selector incidentally matches more than one element, and one of those elements happens to match the assertion criteria.
Obviously this can be avoided with well written selectors, or use of .first()
or .last()
if we expect to return more than one, or .each()
if we want to explicitly assert multiple elements. I’m primarily looking for confirmation on what the behavior is so I understand how Cypress works in these situations where multiple elements are selected (intentionally or otherwise.)
2
Answers
For the assertions in
.should()
, I believe that Cypress operates in the same way that ChaiJQuery operates, which switches between validating the first element meets the criteria, or that any element meets the criteria.For example, attr
vs. hidden
For other Cypress commands, you’ll have to investigate their behaviors. For an example with
cy.click()
:So, the tl;dr answer is each chained command behaves differently.
It depends on the assertion.
There is an example here Multiple elements
The
include.text
will apply to any one of the elements, but thehave.text
applies to all elements combined.What about
be.disabled
?From chai-jquery
As an opposite example,
In general, Cypress follows the rules set down by the library it uses, so this documentation is a good reference for your question.