Test Writer Nestjs
ASecurityWrite behavioral tests for NestJS hexagonal backends. Jest, ts-jest, Supertest on the real AppModule. Golden rule: ALL tests go through a REAL behavioral entry point — Supertest on the real AppModule when a route exists, or a real published message/job when a processor triggers the logic. NO unit tests, NO integration tests, NO test/unit dir: ONLY test/behavioral/. testcontainers for real infra, mocks only for outbound external adapters (email, Stripe, S3). Use when testing a route, controlle...
- 3 stars
- 0 votes
- 0 copies
- 0 views
- Added December 3, 2026
Works with
Security analysis
100/100Pro scans all 6 files and shows the line behind each finding
npx -y skills add Kaiohz/ai-driven --skill test-writer-nestjs --agent claude-codeAre you the author of Test Writer Nestjs?
Add the live security badge to your README. It updates with every re-scan.
[](https://www.skillsdirectory.com/skills/kaiohz-test-writer-nestjs)---
name: test-writer-nestjs
description: "Write behavioral tests for NestJS hexagonal backends. Jest, ts-jest, Supertest on the real AppModule. Golden rule: ALL tests go through a REAL behavioral entry point — Supertest on the real AppModule when a route exists, or a real published message/job when a processor triggers the logic. NO unit tests, NO integration tests, NO test/unit dir: ONLY test/behavioral/. testcontainers for real infra, mocks only for outbound external adapters (email, Stripe, S3). Use when testing a route, controller, use case, service, or adapter in a NestJS app."
---
# Test Writer — NestJS
Write clear, maintainable tests for a NestJS hexagonal backend with Jest, ts-jest, and Supertest.
## Use this skill when
- Testing a route, controller, use case, service, or adapter in a NestJS app
- You need mock provider factories for external adapters
- You're unsure whether to mock or use the real implementation
## Do not use this skill when
- The task is project structure → use `hexagonal-nestjs-patterns`
- The task is async/RxJS design → use `async-nestjs-patterns`
- The task is Python or React testing → use `test-writer-python` / `test-writer-react`
## 🎯 Golden Rule (non-negotiable)
- **ALL tests go through a REAL behavioral entry point, in this strict order**:
1. **Route exists → test from the route**: one HTTP request via Supertest against the REAL `AppModule` (never a rebuilt TestingModule that re-declares internal providers). Assert the HTTP response AND observable side effects (DB state, emitted events).
2. **No route but a consumer/processor/scheduler triggers the logic → test through that entry point**: publish a REAL message to the real broker testcontainer (Bull queue job, Kafka/NATS message, cron tick) and wait for observable side effects — never invoke the processor/use case directly. A use case only reachable from a processor or cron is tested exactly the way production triggers it.
3. **No route and no consumer? Never delete the logic and never invent an artificial endpoint just to test it.** Keep the logic as-is but do NOT write a direct unit test for it: coverage of such helpers, normalizers, or validators comes from the routes/processors that (directly or transitively) exercise them. If today nothing exercises them, simply leave them untested rather than bypassing the golden rule.
- The whole chain runs real: Controller/Processor → Use Case → Port → Repository.
- **A use case/service/adapter is NEVER the direct test subject** — it is covered through its entry point. If you find yourself instantiating a use case or service in a test, STOP and test through the entry point.
- **Real implementations** for ALL internal components (controllers, processors, use cases, services, ports, repositories, domain objects, TypeORM entities) — never mock or rewire an internal layer.
- **Mocks** ONLY for outbound adapters toward external systems (third-party APIs, email, S3, Stripe, payment gateways) — via `overrideProvider` on the adapter class only.
- **Real infrastructure** via testcontainers (Postgres / Redis / Kafka / RabbitMQ / LocalStack) — Docker is a hard requirement — see `references/testcontainers.md`. If Docker is unavailable, fail fast with a clear error; never silently fall back.
A stub that diverges silently from the real implementation produces tests that pass but don't detect real regressions. Testing through the real AppModule exercises the exact wiring production uses (guards, pipes, interceptors, exception filters, DI) — cost stays low and confidence high.
## 🗂️ Test layout (non-negotiable)
```
test/
├── setup.ts # real AppModule + testcontainers + Supertest + auth helpers
├── fixtures/
│ └── external.ts # mocks for external adapters (configurable failures)
├── behavioral/
│ └── <feature>/
│ └── <endpoint>.spec.ts # EVERYTHING behaviorally — all branches, routes or processors only
```
- `behavioral/<feature>/<endpoint>.spec.ts` — one Supertest-based file per entry point (route or processor), all branches covered (happy path, validation, auth, conflicts, external failures). This is the default and THE ONLY kind of test suite.
- NO `test/unit/` directory: every behavior must be exercised through a real entry point. Logic exercised by neither stays as-is but is simply not directly tested — never delete it, never invent an endpoint for it.
- `setup.ts` — the only place for shared setup: real AppModule bootstrap, testcontainers infra, auth helpers (register/login via the real API → reusable auth headers).
## 🎯 Workflow
1. **Ask for context** — which route/endpoint (feature) needs testing?
2. **Read the source code** — the controller AND the whole chain it triggers (use case, ports, adapters, entities).
3. **Coverage audit — feature surface ONLY** — before writing ANY file, search the existing suite (grep/glob `test/behavioral/`) for specs already covering the FEATURE UNDER TEST, matching entry-point identifiers ONLY (route path, endpoint name, processor name, feature directory). NEVER audit beyond the feature surface — no whole-suite review, no coverage redesign of unrelated features. Outcomes, in preference order: (a) existing specs already verify the feature behaviors → run those specs, report the mapping (behavior → test), and write NOTHING new; (b) partial coverage → extend the matching spec files in place with the missing cases; (c) an entry point has no coverage → create `test/behavioral/<feature>/<entry_point>.spec.ts`. In EVERY outcome, print a compact COVERAGE_MATRIX at the end: feature-surface item (route/processor/acceptance criterion) → existing test name or `NEW`.
4. **Classify dependencies** — internal → real impl (already wired in the AppModule); external → `overrideProvider` with factories from `test/fixtures/external.ts`.
5. **Load templates** — `references/router-test.md` (PRIMARY: behavioral test via Supertest on the real AppModule, in `test/behavioral/<feature>/<endpoint>.spec.ts`); `references/processor-test.md` when the logic is triggered by a queue/processor/scheduler (real message/job → side effects); `references/testcontainers.md` for real infrastructure; `references/setup.md` (jest config, fixtures, auth helpers). Never delete logic with no route/processor and never invent an artificial entry point just to test it.
6. **Write tests** — AAA pattern, explicit names, one logical behavior per test. Act = one Supertest request; Assert = status + body + persistence via the real repository.
7. **Run** — only the affected feature specs (reused + extended + new), never the full suite unless the change touches shared fixtures (`setup.ts`, `test/fixtures/`) — see `references/commands.md`.
## 🛡️ Edge cases (mandatory coverage)
Every test suite MUST cover edge cases, not just the happy path. For each route under test, include tests asserting the correct HTTP status + error body:
- **Validation** — missing required field, wrong type, Zod schema failure, out-of-range enum, oversized payload → 400/422
- **Auth / permissions** — unauthenticated → 401, wrong role → 403, foreign resource → 404
- **Not found / conflicts** — unknown id → 404, already-exists → 409, already-deleted, duplicate creation
- **Empty / boundary values** — empty array, page 1 / page size boundary, offset equals total count, single-element collections
- **Concurrency / race conditions** — duplicate concurrent requests, idempotency key replay (when applicable)
- **External adapter failure** — outbound adapter throws, returns error, times out, returns empty → the route still responds correctly (no silent swallow, no 500)
If the feature under test has domain invariants or business rules, add at least one test per invariant that violates it via the API and asserts the correct error response.
## What you never do
- Create a NEW test file when an existing spec already covers the entry point — extend it in place or reuse it and report the mapping instead
- Audit specs beyond the feature under test — no whole-suite review, no coverage redesign of unrelated features
- Test a use case in isolation when it is exposed via an HTTP route — test it from the router instead
- Test a use case, service, or infrastructure adapter DIRECTLY (instantiated in the test), ever — go through the entry point (route = Supertest request; processor = real published message/job)
- Write a direct unit test for pure domain logic, scripts, or helpers that nothing exercises — leave it untested rather than bypassing the golden rule; never delete the logic and never invent an artificial endpoint
- Mock internal components to force a use case/adapter into a testable state (e.g. override an internal `HttpService` wrapper used by an external adapter) instead of mocking the external API at the adapter boundary
- Place a test anywhere outside `test/behavioral/<feature>/` — behavioral is the ONLY location
- Rebuild a TestingModule that re-declares controllers/use cases/repositories of the real chain — import the real AppModule and `overrideProvider` ONLY external adapters
- Use `@nestjs/testing`'s `overrideProvider` on internal classes (use cases, services, repositories)
- Provide an `InMemoryXxxRepository` or any other fake for an internal implementation
- Mock a use case, domain service, domain object, or TypeORM repository with `jest.fn()`
- Assert on internal implementation details (spy on a private method); use `jest.spyOn` on internal components to verify they were called
- Mock something just to make a test pass
## Related skills
- `hexagonal-nestjs-patterns` — project structure, ports, Zod usage
- `async-nestjs-patterns` — async/RxJS/event/queue patterns (test the patterns you implement)
## References
- `references/router-test.md` — behavioral test from the router via Supertest on the real AppModule (PRIMARY template)
- `references/processor-test.md` — behavioral test through a queue processor/consumer: real message or job published to the real broker, observable side effects only (SECONDARY template)
- `references/setup.md` — jest config, test structure (`test/behavioral/<feature>/`), external fixtures, auth helpers
- `references/testcontainers.md` — real infrastructure for tests (Postgres, Redis, Kafka, RabbitMQ, LocalStack)
- `references/commands.md` — jest commands (run, watch, coverage, behavioral)
Files in this skill
- SKILL.md
- references/commands.md
- references/processor-test.md
- references/router-test.md
- references/setup.md
- references/testcontainers.md
Attribution
Related skills
View all in ai-agents →Comments
Loading comments…
Newsletter
Get the weekly list of safe new skills, and the ones we pulled.