Александр
Александр

Reputation: 317

how can i count the elements so i can use the value later?

Html:

<tbody class="ant-table-tbody">
   <tr class="ant-table-row"> 1 </tr>
  <tr class="ant-table-row"> 2 </tr>
        ...
  <tr class="ant-table-row"> n </tr>
</tbody>

JS:

let count = cy.get('.ant-table-tbody').find('.ant-table-row')
if (count >= 0) {
   cy.log(`There are ${count} elements`)  
} else {
   cy.log('There are no elements')
}

When I get .ant-table-tbody element I need to count .ant-table-row elements. If count more than '0' cy.log count of elements, if '0' element should cy.log - No elements. How can I do it?

Upvotes: 0

Views: 1071

Answers (3)

Leta Waldergrave
Leta Waldergrave

Reputation: 689

Ok, I think you ask to know when there's zero rows as well as > 0, so

cy.get('.ant-table-tbody')
.then($tbody => {
  const count = $tbody.find('.ant-table-row').length // jquery find won't fail
  if (count > 0) {
    cy.log(`There are ${count} elements`)  
  } else {
    cy.log('There are no elements')
  }
})

If zero rows are not possible, other answers are simpler.

Upvotes: 2

Alapan Das
Alapan Das

Reputation: 18629

You can apply an greater than 0 assertion and add custom log message like this:

cy.get('.ant-table-tbody')
  .find('.ant-table-row')
  .its('length')
  .should('be.gt', 0, 'The element count is greater than 0')

Or, if you want to assert the count to be greater than and equal to 0, you can

cy.get('.ant-table-tbody')
  .find('.ant-table-row')
  .its('length')
  .should('be.gte', 0, 'The number of elements is greater and equal to 0')

Upvotes: 0

Fody
Fody

Reputation: 31974

You can use the same method as your question last July, using an alias

cy.get('.ant-table-tbody')
  .find('.ant-table-row')
  .its('length')
  .as('rowCount')

cy.get('@rowCount')
  .then(count => {
    if (count) {
      cy.log(`There are ${count} elements`) 
    ...
  })

or directly after the find

cy.get('.ant-table-tbody')
  .find('.ant-table-row')
  .its('length')
  .then(count => {
    if (count) {   // not count >= 0, because 0 means no elements
      cy.log(`There are ${count} elements`) 
    ...
  })

All code using count must be inside a .then()

Upvotes: 2

Related Questions