Test isolation / setup and teardown

Every test starts from a clean known state and leaves nothing behind, so tests cannot poison each other or depend on running order.

tests messing with each otherclean up between testsbeforeEach afterEachit passes alone but fails in the suitereset the database between teststests fail in a different orderleftover state from the last testsetup and teardown hooks

See it

Live demo coming soon

What it is

Test isolation means each test starts from a known state and leaves nothing behind, so no test can depend on another test having run first. Setup and teardown are the machinery: hooks like beforeEach and afterEach in Vitest, Jest, or Mocha, fixtures in pytest and Playwright, that build fresh state before the test and dismantle it after. The smell that tells you it is missing is famous: the test passes on its own, fails inside the suite, or fails only when the runner shuffles the order or shards across machines.

The state that leaks is rarely just database rows. Module-level variables and caches, a global store, localStorage, mocked timers, spies that were never restored, environment variables, the DOM from the last render, an open server or socket. Practical fixes, cheapest first: create data inside the test with unique values instead of relying on a shared seed, wrap each test in a database transaction and roll it back, reset mocks and modules in a global beforeEach, and let libraries do their own cleanup (Testing Library unmounts automatically when the runner exposes an afterEach).

Gotcha: prefer building clean state in setup over promising to clean it in teardown. Most runners do still run teardown after a test fails or times out, but nothing runs it when the process crashes, CI kills the job, or the runner itself falls over, and once the cleanup is skipped every later test inherits the mess. Second gotcha: beforeAll looks like a performance win but it shares one object across tests, so the first test that mutates it silently couples the rest. Use it only for genuinely read-only setup, like starting a container or compiling a schema.

Ask AI for it

Fix test isolation in [TEST FILE / SUITE]: the tests currently share state and pass or fail depending on order. Give each test its own state. Move shared mutable setup out of beforeAll into beforeEach; create test data inside each test with unique values (random suffix or factory) instead of a shared seeded fixture; wrap database work in a transaction that rolls back after each test; and add a global beforeEach that clears mocks, restores spies, resets fake timers, clears localStorage, and resets any module-level cache. Remove any test that reads data another test created. Then run the suite with a randomized order and in parallel to prove the isolation holds, and report anything still failing.

You might have meant

hermetic testflaky testtest fixtureseed dataparallelization sharding