Verify the number of items in a list on the webpage
Preconditions (2)
✅ Expected Result: The list contains exactly 5 items with class 'list-item'
describe('Length assertions test', () => { it('should verify the number of list items is 5', () => { cy.visit('https://example.com/list-page'); cy.get('#item-list .list-item').should('have.length', 5); }); });
The test opens the webpage using cy.visit(). Then it locates all elements with class list-item inside the container with id item-list using cy.get('#item-list .list-item'). The assertion .should('have.length', 5) checks that exactly 5 such elements exist. Cypress automatically waits for elements to appear, so no explicit waits are needed. Using id and class selectors ensures the test is clear and maintainable.
Now add data-driven testing with 3 different expected lengths for different pages
cy.get('.item').should('have.length', 3) check on a webpage?cy.get() usagecy.get('.item') selects all elements with the class 'item' on the page.should('have.length', 3) assertionshould('have.length', number).cy.get('.todo-item').should('have.length', 4)
cy.get('.todo-item').eq(0).should('contain.text', 'Buy milk')todo-item?cy.get('.card').should('have.length', 5)should('have.length', 5) is correct. Cypress counts elements matching the selector, so counting works. Manual refresh is not needed.should('have.length.gte', 2) for "greater than or equal" and should('have.length.lte', 5) for "less than or equal".Pass the test and this pattern moves unknown