Parallel tests finish faster but fail unpredictably if they share state: a database, a port, a temp file or a global variable. Isolation makes each test independent so the suite is both fast and reliable, and it exposes hidden coupling.
Before you start
You should be comfortable with test suites and shared resources. This article covers isolation strategies.
Step-by-step walkthrough
Step 1: Remove shared mutable state
Tests that write to a module-level variable or a shared cache interfere when run together. Give each test its own instance, or reset the shared state in setup and teardown. A test that passes alone but fails in parallel is a shared-state smell.
Step 2: Isolate external resources
Use a unique schema or database per worker, a random free port, and a temp directory per test. Containers or ephemeral schemas give each worker a clean environment. Hard-coded ports and shared tables are the usual collisions.
Step 3: Randomize order to expose coupling
Running tests in a random order surfaces hidden dependencies between tests, where one test relies on another’s leftover state. A green suite in a fixed order can hide real coupling that appears under parallel execution.
Worked scenario
Each worker gets an isolated resource.
const dbName = `test_${process.env.WORKER_ID ?? '0'}`;
beforeAll(async () => { await createSchema(dbName); });
afterAll(async () => { await dropSchema(dbName); });Walk through the example
Each worker creates and drops its own schema, so parallel tests do not share tables. No global state leaks between them, so the suite runs fast without interference. Randomizing order then confirms there is no dependency on a specific sequence.
Common mistake
A shared database or cache across workers, which causes flaky failures that depend on timing. Another is hard-coded ports, so two workers try to bind the same port. Assuming a passed suite is isolated without running in parallel or random order.
Verify the behavior
Run the suite in parallel and confirm it passes consistently. Randomize order and confirm no failures, which would indicate hidden coupling. Run a single test in isolation and confirm it still passes.
Interview exercise
Why can a test pass alone but fail in a parallel run?
Answer and reasoning
Because it depends on state that another test also touches. Alone, it has the state to itself; in parallel, another test reads or writes the same database row, file or variable, and the two interfere. The failure points to shared mutable state that isolation must remove.
Continue learning
Compare isolation in Fixture isolation and determinism in Async determinism. Read the xUnit patterns on shared fixtures and try the Testing interview questions.