0
0
Cypresstesting~15 mins

Length assertions in Cypress - Build an Automation Script

Choose your learning style9 modes available
Verify the number of items in a list on the webpage
Preconditions (2)
Step 1: Open the webpage URL
Step 2: Locate the list container with id 'item-list'
Step 3: Count the number of child elements with class 'list-item' inside the list container
Step 4: Verify that the count matches the expected number (5)
✅ Expected Result: The list contains exactly 5 items with class 'list-item'
Automation Requirements - Cypress
Assertions Needed:
Assert that the number of elements with class 'list-item' inside '#item-list' is 5
Best Practices:
Use cy.get() with proper selectors
Use .should('have.length', expected) for length assertion
Avoid hardcoding waits; rely on Cypress automatic waits
Use clear and maintainable selectors (id and class)
Automated Solution
Cypress
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.

Common Mistakes - 3 Pitfalls
{'mistake': 'Using cy.get() with an incorrect or overly generic selector', 'why_bad': 'This can select wrong elements or multiple unrelated elements, causing flaky tests or false results.', 'correct_approach': "Use specific selectors like '#item-list .list-item' to target exactly the intended elements."}
{'mistake': "Using .should('have.length', '5') with the length as a string", 'why_bad': 'The assertion expects a number, so using a string can cause the test to fail or behave unexpectedly.', 'correct_approach': "Always pass the expected length as a number, e.g., .should('have.length', 5)."}
Adding fixed waits like cy.wait(500) before assertions
Bonus Challenge

Now add data-driven testing with 3 different expected lengths for different pages

Show Hint