In Cypress how to count a selection of items and get the length?

Katharine Osborne picture Katharine Osborne · Oct 20, 2017 · Viewed 66k times · Source

I'm starting to learn Cypress. I have a 4 row table (with a class of datatable). I can verify the number of rows this way:

cy.get('.datatable').find('tr').each(function(row, i){
        expect(i).to.be.lessThan(4)
})

This is fine, but it seems awkward, since I just want to count the length and don't really need to access the stuff in the rows, and I assume it's faster to do one thing than do 4 things.

If I log the selection (not sure what else to call it):

cy.log(cy.get('.datatable').find('tr'))

it comes out as [object Object] and I'm not quite sure how to deconstruct that, which suggests to me that I'm thinking about this all wrong.

If I try:

expect(cy.get('.datatable').find('tr')).to.have.lengthOf(4)

I get AssertionError: expected { Object (chainerId, firstCall) } to have a property 'length'

If I try:

    expect(Cypress.$('.datatable > tr')).to.have.lengthOf(4)

I get AssertionError: expected { Object (length, prevObject, ...) } to have a length of 4 but got 0 so at least it has a length here?

If I log that method of selection I get Object{4}. I'm not sure where to go from here. It seems like this would be a very common thing to deal with.

Answer

Katharine Osborne picture Katharine Osborne · Oct 20, 2017

Found a solution, This works to check a count of items:

cy.get('.datatable').find('tr').should('have.length', 4)

This does not work with the Cypress.$() method of notation.

Reference: https://docs.cypress.io/guides/references/assertions.html#Length