Reputation: 14841
I am writing functional tests for my JavaScript web application. I don't have much experience writing tests using Cypress to be honest. What I am trying to test now is that if the user can see a particular text message on the page for the X number of times.
This is my assertion in the test at the moment.
cy.contains('Hello World').should('be.visible')
As you can see, I am testing that if the "Hello World" message is visible to the user. What I would like to also test is that I want to test if the message is seen for 3 times. How can I do that?
Following is my dummy HTML.
<form>
<div>
<div>
<input name="email" />
</div>
<ul>
<li>This is required.</li>
</ul>
</div>
<div>
<div>
<input name="password" />
</div>
<ul>
<li>This is required.</li>
</ul>
</div>
</form>
Upvotes: 1
Views: 3490
Reputation:
You should be able to use
cy.contains('Hello World')
.its('length')
.should('eq', 3)
but this might be a bit fragile, because .contains()
works on child elements as well. Might be better to be more specific - can you show what HTML you are working with?
To search a list, verify the count of <li>
containing "This is required"
cy.get('li:contains("This is required")')
.its('length')
.should('eq', 2)
Yields
.contains() yields the new DOM element it found.
which means Cypress always returns just one element, so we need to move the contains()
into the selector to get an accurate count.
It's always useful to check the Yields paragraph, some commands yield multiple elements and some yield just the first even when multiple match the selector.
Note this will ignore any <li>
with different text.
Upvotes: 1
Reputation: 18586
You can use each()
(Cypress Docs) to iterate through the elements and check for the text and also check the length like this. $list
will contain the no of occurrences of element.
cy.get('ul > li').each(($ele, $list) => {
expect($ele).to.have.text('Hello World')
}).then(($list) => {
expect($lis).to.have.length(3)
})
Upvotes: 1