0
0
Cypresstesting~5 mins

Data cleanup approaches in Cypress

Choose your learning style9 modes available
Introduction

Data cleanup helps keep tests independent and reliable by removing leftover data after tests run.

After creating test data like users or orders to avoid clutter.
Before running tests to ensure a clean starting point.
When tests modify shared data that could affect others.
To prevent database or system overload from too much test data.
Syntax
Cypress
after(() => {
  // cleanup code here
  cy.request('DELETE', '/api/test-data')
})

after() runs once after all tests in a block finish.

You can also use afterEach() to clean after each test.

Examples
Deletes a test user after all tests complete.
Cypress
after(() => {
  cy.request('DELETE', '/api/users/testuser')
})
Runs cleanup after each test to reset data.
Cypress
afterEach(() => {
  cy.request('POST', '/api/cleanup')
})
Resets database before tests start to ensure clean state.
Cypress
before(() => {
  cy.request('POST', '/api/reset-database')
})
Sample Program

This test suite resets the database before tests, creates a user during the test, and deletes that user after all tests finish.

Cypress
describe('User tests with cleanup', () => {
  before(() => {
    cy.request('POST', '/api/reset-database')
  })

  it('creates a new user', () => {
    cy.request('POST', '/api/users', { username: 'testuser' })
      .then(response => {
        expect(response.status).to.eq(201)
      })
  })

  after(() => {
    cy.request('DELETE', '/api/users/testuser')
  })
})
OutputSuccess
Important Notes

Always clean data to avoid tests affecting each other.

Use API calls or database commands for faster cleanup than UI actions.

Be careful to only delete test data, not real data.

Summary

Data cleanup keeps tests independent and reliable.

Use before, after, beforeEach, or afterEach hooks for cleanup.

API requests are efficient for cleaning test data.