Org Skills

nodejs-testing

Design the test strategy for a Node.js/TypeScript back-end service and write the tests — runner choice between Vitest, Jest and node:test, in-process HTTP tests with Fastify inject or supertest, real Postgres and Redis through Testcontainers, outbound HTTP faked with MSW or undici MockAgent, database isolation per test, fake timers, factories, contract tests, coverage and flaky-test triage.

Download .zip Raw Source
When agents use itUse this whenever the user asks how to test a Node route, service, repository, queue worker or NestJS module; sets up vitest.config.ts, jest.config.ts or the test script in package.json; asks about mocking fetch, Prisma or time, testing a BullMQ worker, or what to test; or hits "Jest did not exit", open handles, order-dependent failures or a test that passes locally and fails in CI. Also use it when choosing a runner for a NestJS 12 project.

Install

Copilot (VS Code, Visual Studio, Copilot CLI and github.com) reads skills from the repository — commit them so the whole team gets them.

npx skills add AGCO-Global/org-skills --skill nodejs-testing -a github-copilot
# or with the org installer (adds .github/skills/nodejs-testing):
npx -y github:AGCO-Global/org-skills add skill nodejs-testing

Uses the open skills CLI. Works with Claude Code, Codex, Cursor, Copilot, Gemini CLI, OpenCode, Windsurf and 60+ others — it asks which agent to install into.

npx skills add AGCO-Global/org-skills --skill nodejs-testing
# user-level instead of project-level:
npx skills add AGCO-Global/org-skills --skill nodejs-testing -g

Installs the backend-nodejs-skills plugin, which bundles all Backend / Node.js skills and keeps them updated.

/plugin marketplace add AGCO-Global/org-skills
/plugin install backend-nodejs-skills@org-skills
# or just this skill, in this repository:
npx skills add AGCO-Global/org-skills --skill nodejs-testing -a claude-code

Use Download .zip above, then upload it under Customize → Skills → Upload skill. Team and Enterprise admins can sync this repo as a plugin marketplace instead.

Installs into .agents/skills/, which Codex reads.

npx skills add AGCO-Global/org-skills --skill nodejs-testing -a codex

Installs into Cursor's skills folder.

npx skills add AGCO-Global/org-skills --skill nodejs-testing -a cursor

Installs into Gemini CLI's skills folder.

npx skills add AGCO-Global/org-skills --skill nodejs-testing -a gemini-cli

Nothing to install. Press Download .zip above, unzip it, and drop the nodejs-testing folder into your tool's skills folder — .claude/skills/, .github/skills/, .cursor/skills/ or .agents/skills/. Step-by-step, per tool: How to use it. For any other tool with rules or custom prompts, Copy SKILL.md and paste it in — it is plain Markdown.

The npx commands need Node.js 20+ and use your normal git sign-in to GitHub, so they work while the repository is private. Without Node.js, see the No Node.js tab — a skill is a folder of Markdown, so copying it in works just as well.

Skill contents

Node.js Testing

Targets: Node 24 LTS, Vitest 5, Jest 30, node:test, Testcontainers, MSW 2, Prisma 7 · Verified: 2026-09 against https://vitest.dev/config/ and https://nodejs.org/api/test.html

Back-end tests earn their keep by catching wiring, data and contract bugs — exactly the bugs mocks hide. Favour fast in-process tests that go through real routing, real validation and a real database, and fake only what crosses a network boundary you do not own.

1. Decide first

Question Default Change when
Runner Vitest for new ESM projects, including NestJS 12 (nest new picks Vitest for ESM) An existing CommonJS Jest suite — keep it; a library with no dependencies → node:test
Where does confidence come from? In-process HTTP tests through the real app A pure domain rule needs no HTTP; test it directly
Database Testcontainers with the real engine Never SQLite standing in for Postgres in an integration test
Outbound HTTP MSW 2 with onUnhandledRequest: 'error' Low-level undici behaviour → MockAgent; legacy suite → nock 14+
Your own modules Inject fakes through the composition root Module mocks (vi.mock) only for an SDK singleton with no injection point
Isolation between tests Truncate, or a schema per worker Transaction-per-test only when the code under test does not open its own
Time Fake timers, or an injected clock port Never fake timers in a test that drives a real database driver
Coverage v8 provider, gate on changed code Istanbul when you need exact branch mapping

2. What each layer is for

Layer Tooling Catches
Static tsc --noEmit, @typescript-eslint/no-floating-promises Type and async mistakes, before a test runs
Unit Vitest + factories Domain rules, mappers, schemas, pure use cases
Integration (in process) app.inject() / supertest + Testcontainers Route → validation → service → SQL → error mapping, together
Contract Pact, or OpenAPI response validation Breaking a consumer without noticing
End-to-end Playwright (request fixture) or an HTTP smoke suite A few critical journeys against a deployed build

The integration layer is where most of the value is: it is the only place schemas, SQL and error handling are exercised at the same time.

3. In-process HTTP tests

app.ts builds the app without listening (nodejs-development §2), so a test can drive it with no socket, no port and no race.

import { describe, expect, it } from 'vitest';
import { buildApp } from '../src/app.js';

describe('POST /orders', () => {
  it('creates an order and returns 201 with a location header', async () => {
    const app = buildApp();
    await app.ready();

    const response = await app.inject({
      method: 'POST',
      url: '/orders',
      payload: { sku: 'A1', qty: 2 },
      headers: { authorization: `Bearer ${await tokenFor(user)}` },
    });

    expect(response.statusCode).toBe(201);
    expect(response.headers.location).toMatch(/^\/orders\//);
    expect(response.json()).toMatchObject({ sku: 'A1', qty: 2, status: 'pending' });

    await app.close();
  });
});

Express, Hono and NestJS use supertest(app); NestJS builds the app with Test.createTestingModule(...).compile() and replaces dependencies with .overrideProvider(PaymentGateway).useValue(fake). Hono also has app.request().

Assert the status, the body shape and the side effect (the row exists, the message was enqueued), then write the unhappy cases — 400, 401, 403, 404, 409. Those are the ones that regress silently.

4. Real dependencies, faked externals

// tests/global-setup.ts — one container per run, migrations applied once
import { PostgreSqlContainer } from '@testcontainers/postgresql';

export async function setup() {
  const pg = await new PostgreSqlContainer('postgres:17-alpine').start();
  process.env.DATABASE_URL = pg.getConnectionUri();
  await runMigrations(process.env.DATABASE_URL);
  return async () => pg.stop();
}
// tests/msw.ts
import { http, HttpResponse } from 'msw';
import { setupServer } from 'msw/node';

export const server = setupServer(
  http.post('https://pay.example.com/charges', () =>
    HttpResponse.json({ id: 'ch_1', status: 'authorised' }, { status: 201 })),
);

beforeAll(() => server.listen({ onUnhandledRequest: 'error' }));
afterEach(() => server.resetHandlers());
afterAll(() => server.close());

onUnhandledRequest: 'error' is the line that matters: without it a forgotten stub silently calls the real API from CI. With Prisma 7, the test setup must load environment variables itself and point prisma.config.ts at the container's URL — Prisma no longer reads .env automatically.

Use real Postgres and Redis; fake third-party HTTP, email and the clock. Do not mock your own repository to test a handler — then no SQL is ever executed and the test proves nothing about the query.

5. Isolation, time and async

  • Isolate with TRUNCATE … RESTART IDENTITY CASCADE between tests (works with any code), a schema per worker (test_${process.env.VITEST_POOL_ID}) for parallel files, or a rolled-back transaction when the code under test does not manage its own.
  • Every test builds what it asserts on, through factories with sensible defaults (buildOrder({ status: 'paid' })). Seed randomness so a failure reproduces.
  • Fake timers (vi.useFakeTimers(), vi.setSystemTime(), vi.advanceTimersByTimeAsync()) for retry delays and scheduled work; restore them in afterEach.
  • await the thing under test, and assert rejections with await expect(p).rejects.toThrow(NotFoundError). A missing await makes a test pass while the assertion never runs — the most common false green in a Node suite.
  • Queue workers: call the processor function directly for unit tests; for integration, run the worker against a real Redis container and await its completion event. Never sleep.

6. Deliverable format

## Behaviours   happy path, validation, auth, not found, conflict, dependency failure
## Setup        helpers reused (buildApp, factories, containers, MSW handlers) and any added
## Tests        one `it` per behaviour, named as a sentence, full compiling TypeScript
## Run          the exact command, and prerequisites (Docker, env vars)

Checklist

  • Behaviours listed before the first test was written.
  • Integration tests run through the real app with a real database engine.
  • Unhandled outbound requests fail the test rather than reaching the network.
  • Each test creates its own data; no order dependency, no shared mutable fixture.
  • Every async call is awaited; rejections asserted with rejects.
  • Time is faked or injected; no sleep anywhere.
  • The app is never listening on a fixed port in a test.
  • Containers start once per run, not per test.
  • TZ=UTC and a seeded random source in CI.
  • Coverage gates on changed code, not a global percentage.

Anti-patterns

  • Mocking the repository to test a handler → real database; otherwise the SQL is untested.
  • SQLite standing in for Postgres → different dialect and constraints; false confidence.
  • Calling a real third-party API → MSW with onUnhandledRequest: 'error'.
  • sleep/setTimeout to wait for an effect → fake timers, or poll with a deadline.
  • app.listen() on a fixed port in tests → app.inject() or supertest against the instance.
  • Starting a container in beforeEach → once in global setup; reset data between tests instead.
  • Snapshotting a whole JSON response with ids and timestamps → assert the fields that matter.
  • vi.mock on your own modules → inject a fake through the composition root.
  • Coverage gamed with assertion-free tests → gate on changed code and review the assertions.

Go deeper

  • references/runner-setup.md — Vitest, Jest and node:test configuration side by side (pools, ESM, TypeScript, projects for a monorepo), the NestJS 12 testing module under ESM, and the runner-specific flags for finding open handles.
  • references/fixtures-and-contracts.md — global setup with Testcontainers and Prisma 7, database isolation strategies compared, factories, BullMQ workers against real Redis, Pact and OpenAPI response validation, Stryker mutation testing, and the flaky-test triage table.
  • Sibling skills: nodejs-development for the code under test, nodejs-architecture for the seams that make it testable, nodejs-performance for load tests, api-design for contract rules, backend-code-review for reviews.

References

Deeper material the agent loads only when needed.