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

前端 未结 5 1987
Happy的楠姐
Happy的楠姐 2020-12-29 19:15

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\         


        
相关标签:
5条回答
  • 2020-12-29 19:47

    One option is to use "have.length" ...

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

    ...another option is to use should

    cy.get('.datatable tr').should(($tr) => {
        expect($tr).to.have.length(4)
    })
    

    ...or then (synchronous queries)

    cy.get('.datatable').then(($table) => {
      // synchronously query to find length of elements
      expect($table.find('td').length).to.equal(4)
    })
    
    0 讨论(0)
  • 2020-12-29 19:52

    From the cypress API docs .should() section, using an arrow function:

    cy.get('.datatable').find('tr').should(($listOfElements) => {
       expect($listOfElements).to.have.length(4)
       // any other assertions, for example the below one
       // expect($listOfElements).to.have.any.keys('key1', 'key2')
    })
    

    This approach will allow you to use Chai BDD notation and assert more than one thing on your list of elements.

    0 讨论(0)
  • 2020-12-29 19:53

    You can also get the length of a selection of items through its property, for example:

    cy.get('.datatable').find('tr').its('length').should('eq', 4)
    cy.get('.datatable').find('tr').its('length').should('be.gte', 4)
    

    In addition to should('have.length', 4)

    I tested with Cypress version 3.1.0 and 3.2.0.

    0 讨论(0)
  • 2020-12-29 19:56

    if you want more flexible and have a dynamic result use this.

    cy.get('.listings-grid')
      .find('.listing')
      .then(listing => {
        const listingCount = Cypress.$(listing).length;
        expect(listing).to.have.length(listingCount);
      });
    
    0 讨论(0)
  • 2020-12-29 20:04

    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

    0 讨论(0)
提交回复
热议问题