0
0
Cypresstesting~15 mins

Test isolation strategies in Cypress - Build an Automation Script

Choose your learning style9 modes available
Verify that each test runs independently with proper isolation
Preconditions (2)
Step 1: Open the application home page
Step 2: Verify that the counter value is 0
Step 3: Click the increment button once
Step 4: Verify that the counter value is 1
Step 5: Reload the page
Step 6: Verify that the counter value is reset to 0
Step 7: Run a second test that opens the home page
Step 8: Verify that the counter value is 0 without any clicks
✅ Expected Result: Each test runs independently without sharing state. The counter resets to 0 at the start of each test.
Automation Requirements - Cypress
Assertions Needed:
Verify counter value is 0 at test start
Verify counter increments correctly
Verify counter resets after page reload
Verify no state is shared between tests
Best Practices:
Use beforeEach hook to visit the page fresh for each test
Avoid sharing variables or state between tests
Use Cypress commands and assertions consistently
Use clear and maintainable selectors (data-cy attributes)
Automated Solution
Cypress
describe('Test isolation strategies', () => {
  beforeEach(() => {
    cy.visit('http://localhost:3000')
  })

  it('increments counter and verifies reset on reload', () => {
    cy.get('[data-cy=counter]').should('have.text', '0')
    cy.get('[data-cy=increment-btn]').click()
    cy.get('[data-cy=counter]').should('have.text', '1')
    cy.reload()
    cy.get('[data-cy=counter]').should('have.text', '0')
  })

  it('starts with counter at 0 without clicks', () => {
    cy.get('[data-cy=counter]').should('have.text', '0')
  })
})

The beforeEach hook visits the application fresh before each test to ensure no shared state.

The first test clicks the increment button and verifies the counter increments, then reloads the page and verifies the counter resets to 0.

The second test verifies the counter starts at 0 without any clicks, proving tests are isolated.

Selectors use data-cy attributes for stability and clarity.

Common Mistakes - 3 Pitfalls
Not using beforeEach to visit the page fresh
Sharing variables or DOM references between tests
Using brittle selectors like classes or ids that may change
Bonus Challenge

Now add a third test that clicks the increment button twice and verifies the counter shows 2, ensuring isolation from previous tests.

Show Hint