nestjs-testing
Skill12 starsChanged 8 days agoMITView on GitHub
Unit, service and end-to-end tests for a NestJS application with @nestjs/testing - Test.createTestingModule, mocking and overriding providers and global guards, Supertest against the real app, signing test users in, SSE, test databases, Vitest in ESM projects (Jest in CommonJS ones). Use when writing, running or fixing tests in a NestJS application.
- Reads credentials
1 other project uses a version of this, 1 of them edited.
Adopted by
Most recently taken up by
- nestjs/typescript-starteredited, first seen Nov 30, 2026
Other versions1 project uses a version of this.
Word for word · 0
None found.
Edited · 1
- nestjs/typescript-starter★ 2.2k99% same
Wrote their own version · 0
None found.
How matches are found. Word for word: the exact same text. Edited: shares passages with this file (“99% same” means 99% of its five-word phrases also appear here; 10% or more counts). Their own version: similar meaning, or, weakest, the same name. We can’t tell which project had it first. Projects are counted among the 200 most-starred candidates, and mentions are links to the repository we found, up to 50 per site, so both counts are a floor.
In this repository41 other files it gives its agents.
- AGENTS.mdAGENTS.md
- .claude/skills/react-doctor/AGENTS.mdAGENTS.md
- .claude/skills/vercel-react-best-practices/AGENTS.mdAGENTS.md
- CLAUDE.mdCLAUDE.md
- ai-agent-developmentSkill
- angular-developerSkill
- api-design-principlesSkill
- aws-serverlessSkill
- brainstormingSkill
- cavemanSkill
- cognitive-doc-designSkill
- diagram-designSkill
- error-handling-patternsSkill
- frontend-designSkill
- golang-proSkill
- gsap-animationSkill
- impeccable-bridgeSkill
- impeccableSkill
- java-springbootSkill
- judgment-daySkill
- kaizenSkill
- nestjs-authSkill
- nestjs-dataSkill
- nestjs-featureSkill
- nestjs-productionSkill
- nestjsSkill
- product-manager-toolkitSkill
- pr-reviewSkill
- react-doctorSkill
- security-auditSkill
- seo-auditSkill
- shadcn-uiSkill
- social-marketingSkill
- software-architectSkill
- stitch-designSkill
- systematic-debuggingSkill
- tailwind-design-systemSkill
- tddSkill
- ui-ux-pro-maxSkill
- vercel-react-best-practicesSkill
- video-productionSkill
The file
Files
Testing a NestJS app
Docs: https://docs.nestjs.com/fundamentals/testing.md. Recipes, each run with Vitest on the scaffold's config: references/testing.md.
Scope first. When the task says how to test, do that. When it says nothing, cover the behaviour you changed with focused tests (a unit test for a policy or a service rule, one e2e test per new route and its main error) rather than broad e2e suites, and verify the rest by running the app.
Pick the level
| What | How | Speed |
| A policy, a pure function, a mapper | new NotePolicy(fakeQuotas): no Nest at all | ms |
| A service's rules | Test.createTestingModule({ providers: [NotesService, { provide: NotesRepository, useValue: { findById: vi.fn() } }] }) | ms |
| A service with the real policies | the above plus imports: [AuthorizationModule.forRoot()] and a stub AuthenticationContext | ms |
| A route as clients see it | imports: [AppModule], Supertest on app.getHttpServer(), a fresh database | 100s of ms |
Runner
- Projects from
nest neware ESM with Vitest (globals: true):npm testrunssrc/**/*.spec.ts,npm run test:e2erunstest/**/*.e2e-spec.ts. Mocks arevi.fn()/vi.spyOn(); relative imports end in.js. One file:npx vitest run src/notes/notes.service.spec.ts; one test: add-t "name". - CommonJS projects use Jest (
jest.fn()). Follow the project'spackage.json.
Rules that save debugging time
- The testing app doesn't run
main.ts. Pipes, filters, prefixes and versioning set there are missing in tests: put them in oneconfigureApp(app)thatmain.tsand the tests both call, or register them asAPP_PIPE/APP_FILTERproviders. - Module options are read when the module file is imported. Set env variables (database path, secrets) in the Vitest config's
test.env, or importAppModuledynamically after setting them. - A global guard registered with
useClasscan't be replaced in tests. Neither.overrideGuard(ThrottlerGuard)nor.overrideProvider(ThrottlerGuard)touches{ provide: APP_GUARD, useClass: ThrottlerGuard }(checked). Register it asThrottlerGuardplus{ provide: APP_GUARD, useExisting: ThrottlerGuard }, then.overrideProvider(ThrottlerGuard).useValue({ canActivate: () => true })works. Or keep the guard and give tests a limit they won't reach. - Sign users in cheaply. Override
PasswordHasherwithnew PasswordHasher({ logN: 10 })(the default costs ~0.3 s and 128 MiB per hash); mint a bearer token withapp.get(TokenService).issue(user.id); run service code as a user withapp.get(AuthenticationContext).run({ user }, fn). Keep one test that signs in through the real route. - One database per test file. Vitest runs files in parallel: a shared SQLite file or schema makes them interfere. Create a temporary file (or schema) per file, apply the migrations, delete it afterwards.
- No ports, no leftovers.
await app.init()andrequest(app.getHttpServer())need no port;afterAll(() => app.close())closes connections and timers. Leave no server or watcher running when you finish. - Time-dependent code (reminders, expiry, rate windows): inject a clock or the delay, rather than sleeping in tests.
- Test what the client sees in e2e tests: status codes, bodies, headers. Assert the exact status the contract names (
expect(201)on a create,expect(200)on a sign-in), which also catches@Post()'s default 201.
When tests fail to start
Nest can't resolve dependencies of NotesService (?)in a unit test: the testing module lacks a provider. Add auseValuestub for it, oruseMocker(() => ({}))for everything missing.- The app works but the test module doesn't: something is registered in
main.tsonly (see above), or env variables are read before the test sets them.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

