SkillByAIOpen interactive version →

Lesson 17 / 25

Test Data and Resetting State

Every test owns its world.

Isolation by design

Both tools isolate the browser by default: Playwright gives each test a new browser context, and Cypress (since version 12) enables testIsolation, clearing cookies and storage and resetting the page before each test. Backend state is your responsibility. Strategies: create the data a test needs through the API in a hook, use unique identifiers so parallel tests do not clash, reset or reseed a dedicated test database before a run, or wrap tests in tenants or accounts created per worker. Avoid relying on test order or on data created by another test. Control time with Playwright's clock API (page.clock, in recent versions) or Cypress cy.clock() and cy.tick().

Per-test data through the API

Playwright fixture that creates and deletes a project.

import { test as base, expect } from '@playwright/test';

type Project = { id: string; name: string };

export const test = base.extend<{ project: Project }>({
  project: async ({ request }, use, testInfo) => {
    const name = `proj-${testInfo.workerIndex}-${Date.now()}`;
    const res = await request.post('/api/projects', { data: { name } });
    expect(res.ok()).toBeTruthy();
    const project: Project = await res.json();

    await use(project);

    await request.delete(`/api/projects/${project.id}`);
  },
});

test('renames a project', async ({ page, project }) => {
  await page.goto(`/projects/${project.id}`);
  await page.getByLabel('Name').fill(`${project.name}-renamed`);
  await page.getByRole('button', { name: 'Save' }).click();
  await expect(page.getByRole('heading')).toHaveText(`${project.name}-renamed`);
});

Clean up before, not only after

If a run crashes, teardown may never happen. Resetting or seeding at the start of a run (or per test) keeps the next run predictable.

Quick check: Why add the worker index or a timestamp to created data names?

  • Because the API rejects short names
  • To make the HTML report sort alphabetically
  • So tests running in parallel do not collide on the same records
  • To slow tests down deliberately
Answer

So tests running in parallel do not collide on the same records — Unique data enables parallel, order-independent tests.