Verify that each test runs independently with proper isolation
Preconditions (2)
✅ Expected Result: Each test runs independently without sharing state. The counter resets to 0 at the start of each test.
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.
Now add a third test that clicks the increment button twice and verifies the counter shows 2, ensuring isolation from previous tests.
beforeEach runs before every test, ideal for resetting state.before runs once before all tests, after and afterEach run after tests, so they don't reset state before tests.describe('My Tests', () => {
beforeEach(() => {
cy.visit('/login')
})
it('Test A', () => {
cy.get('#username').type('user1')
cy.get('#password').type('pass1')
cy.get('button').click()
cy.url().should('include', '/dashboard')
})
it('Test B', () => {
cy.get('#username').type('user2')
cy.get('#password').type('pass2')
cy.get('button').click()
cy.url().should('include', '/dashboard')
})
})beforeEach here?beforeEach runs before every test, so it visits the login page before Test A and Test B.beforeEach to reset state, but tests still fail due to shared data. What is the likely mistake?before is used, it runs once before all tests, so state is not reset before each test.beforeEach to reset state and avoid shared data ensures each test is independent and reliable.Pass the test and this pattern moves unknown