Reputation: 2618
In Cypress I have a bunch of articles, and I would like to test that they all have at least X characters or Y words inside the .content
-div.
The structure of the .content
-div looks like this:
<div class="content">
<p>
Lorem ipsum dolor sit amet.
</p>
<p>
Adipiscing elit suspendisse eu nibh.
</p>
</div>
If I current do this:
cy.get( '.content' ).its( 'length' ).should( 'be.gte', 5 );
But this yields the error:
expected 2 to be at least 5
Since it counts the tags inside the div, the two <p>
-tags. Instead of counting the words inside these <p>
-tags.
How do I count all words/characters (either is fine), in all children (and ideally also childrens children recursively)?
... So a function that returned 10
for above-given example.
It could be super-cool to have a command with it.
Upvotes: 0
Views: 827
Reputation: 4405
You can count the spaces,
cy.get('.content')
.find('p') // children + children's children (any <p> under .content)
.each($p => {
const words = $p.text().split(' ').length +1
expect(words.length).to.be.gte(5)
})
Upvotes: 2
Reputation: 18624
You can directly iterate over the p
tags using each
and then invoke text and then assert its length.
cy.get('.content > p').each(($ele) => {
cy.wrap($ele).invoke('text').its('length').should('be.gte', 5)
})
Upvotes: 1
Reputation: 32062
I would use a word regex and check the match length.
cy.get('.content')
.invoke('text') // include children
.match(/[\w-]+/g) // match words
.its('length)
.should('be.gt', 5)
.and('eq', 10)
Upvotes: 3