# Fixtures, isolation, contracts and flaky tests

Verified 2026-09 against <https://node.testcontainers.org/>,
<https://www.prisma.io/docs/orm/more/upgrade-guides/upgrading-versions/upgrading-to-prisma-7>,
<https://mswjs.io/docs/>, <https://docs.pact.io/> and <https://stryker-mutator.io/docs/stryker-js/introduction/>.

## 1. Global setup with Testcontainers and Prisma 7

```ts
// tests/global-setup.ts — runs once per test run
import { PostgreSqlContainer, type StartedPostgreSqlContainer } from '@testcontainers/postgresql';
import { execFile } from 'node:child_process';
import { promisify } from 'node:util';

const run = promisify(execFile);
let container: StartedPostgreSqlContainer;

export async function setup() {
  container = await new PostgreSqlContainer('postgres:17-alpine').start();
  process.env.DATABASE_URL = container.getConnectionUri();

  // Prisma 7 reads prisma.config.ts and does NOT auto-load .env,
  // so the URL must be in the environment of the CLI process.
  await run('npx', ['prisma', 'migrate', 'deploy'], {
    env: { ...process.env, DATABASE_URL: process.env.DATABASE_URL },
  });
}

export async function teardown() {
  await container.stop();
}
```

One container per run, migrations once. Starting a container per file multiplies start-up by the
number of workers and is the single biggest cause of slow Node integration suites.

Redis for a BullMQ worker works the same way with `@testcontainers/redis`.

## 2. Isolation strategies

| Strategy | How | Trade-off |
|---|---|---|
| **Truncate between tests** | `TRUNCATE "orders", "order_lines" RESTART IDENTITY CASCADE` | Works with any code, including code that opens its own transactions. Slightly slower than a rollback |
| **Transaction per test** | Begin in `beforeEach`, roll back in `afterEach`, inject the transaction as the connection | Fastest, but breaks as soon as the code under test manages its own transaction (which production code does) |
| **Schema per worker** | `search_path=test_${process.env.VITEST_POOL_ID}`, migrate each on first use | Real parallelism with total isolation; setup cost per worker |
| **Database per worker** | One container, several databases | Strongest, slowest to set up |

Default to truncation; move to a schema per worker when parallel files start interfering. Whichever
you pick, no test may depend on rows another test created.

```ts
// tests/setup.ts
afterEach(async () => {
  await db.$executeRawUnsafe(
    'TRUNCATE "orders", "order_lines", "outbox" RESTART IDENTITY CASCADE',
  );
});
```

## 3. Factories

```ts
// tests/factories/order.ts
import { faker } from '@faker-js/faker';

faker.seed(1234);   // deterministic: a failure reproduces

export function buildOrder(overrides: Partial<Order> = {}): Order {
  return {
    id: faker.string.uuid(),
    sku: faker.string.alphanumeric(6).toUpperCase(),
    qty: 1,
    status: 'pending',
    createdAt: new Date('2026-01-01T00:00:00Z'),
    ...overrides,
  };
}
```

Every field has a default; the test overrides only what it asserts on. That is what makes a test
readable ("an order that is already paid") and what keeps a new required column from breaking two
hundred tests.

## 4. Testing a BullMQ worker

```ts
import { Queue, Worker } from 'bullmq';
import { expect, it } from 'vitest';

it('marks the order as invoiced', async () => {
  const connection = { host: redisHost, port: redisPort };
  const queue = new Queue('invoices', { connection });
  const worker = new Worker('invoices', processInvoice, { connection });

  const completed = new Promise<void>((resolve) =>
    worker.once('completed', () => resolve()));

  await queue.add('invoice', { orderId });
  await completed;

  expect(await db.order.findUnique({ where: { id: orderId } })).toMatchObject({ status: 'invoiced' });

  await worker.close();
  await queue.close();
});
```

Await the `completed` event, never a `sleep`. Close both the worker and the queue, or the Redis
connections keep the process alive and the run hangs at the end.

Test the two behaviours `messaging-patterns` asks for: the same job delivered twice produces one
effect, and a permanent failure ends up in the failed set rather than retrying forever.

## 5. Contract tests

**From an OpenAPI document**, when one team owns both ends — cheap and catches most drift:

```ts
import { OpenApiValidator } from 'express-openapi-validator';   // or openapi-response-validator
```

Validate every integration-test response against the published schema, and lint the document itself
in CI with Spectral (`extends: ["spectral:oas"]`). A response that no longer matches the document
fails the build instead of a consumer.

**Pact**, when separate teams own consumer and provider: the consumer generates a pact from its
tests, the provider verifies it against provider states in its own pipeline, and the broker's
`can-i-deploy` gates the release. It is real infrastructure — take it on when independent deployment
is real, not before.

## 6. Mutation testing

```bash
npm i -D @stryker-mutator/core @stryker-mutator/vitest-runner
npx stryker run
```

Coverage says a line ran; mutation testing says an assertion would have caught it being wrong. Point
it at the domain and application code, not the whole repository, and run it on a schedule rather than
per pull request — it runs the suite once per mutant. The surviving mutants are your assertion-free
tests, which is exactly the list you want.

## 7. Flaky test triage

| Symptom | Likely cause | Fix |
|---|---|---|
| "Jest did not exit" / hanging run | Server, pool, Redis client or interval left open | `await app.close()`, close pools in `afterAll`, `.unref()` intervals. Diagnose with the runner's own flag (`runner-setup.md` §6) |
| Passes alone, fails in the suite | Shared rows or module-level state | Truncate per test, schema per worker, `restoreMocks: true` |
| Random timeouts | A missing `await`, a real network call, a container started per test | Await everything, `onUnhandledRequest: 'error'`, containers in global setup |
| Fails only in CI | Time zone, locale, a slower machine, parallel database access | `TZ=UTC`, `InvariantCulture`-equivalent formatting, schema per worker, no wall-clock assertions |
| Fails when files run in a different order | Hidden ordering dependency | Run with `--sequence.shuffle` regularly so it surfaces early |
| Fails right after a dependency bump | A behaviour change, not flakiness | Read the changelog before touching the test |

Two rules keep the suite trustworthy: **never add a retry to make a test green** — it hides a real
intermittent bug and slows every run — and give every skipped test an owner, an issue link and a date
by which it is fixed or deleted.
