Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses and challenges
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Calculator

0

157
Views
How to count length of text in all children of a div in Cypress

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.

7 months ago · Juan Pablo Isaza
3 answers
Answer question

0

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)        
7 months ago · Juan Pablo Isaza Report

0

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)
})
7 months ago · Juan Pablo Isaza Report

0

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)
  })
7 months ago · Juan Pablo Isaza Report
Answer question
Find remote jobs