test-nestjs-jest-testing-module
Skill0 starsChanged 2 months agoMITView on GitHub
Write Unit Tests for NestJS applications using Testing Module and jest
In this repository20 other files it gives its agents.
- AGENTS.mdAGENTS.md
- code-backend-nestjsSkill
- code-frontend-library-reactSkill
- doc-changelog-generationSkill
- doc-design-generationSkill
- doc-domain-generationSkill
- doc-guardrail-generationSkill
- doc-policy-generationSkill
- doc-readme-generationSkill
- git-tbd-for-sddSkill
- git-worktrees-useSkill
- openspec-generate-baselineSkill
- openspec-init-configSkill
- security-auditSkill
- skill-masterSkill
- skill-test-evalsSkill
- test-cypress-cucumberSkill
- test-nestjs-supertestSkill
- test-playwright-cucumberSkill
- test-react-testing-librarySkill
The file
We split this skill into the rules it gives an agent
12 rules. About 0 are common, 2 are distinctive, and 10 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈2
Distinctive · estimate
This author's own choices. Worth a look.
10
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 18
Write unit tests for NestJS applications using Test.createTestingModule and Jest.
- Very specific: line 23
Test services, controllers, guards, interceptors, and pipes in isolation with mocked dependencies (useValue with jest.fn()).
- Very specific: line 29
Not for API integration tests that exercise the full HTTP request/response cycle (use the test-nestjs-supertest skill instead).
- Very specific: line 30
Not for true browser E2E tests that drive a UI (use the playwright/cypress skills instead).
- Very specific: line 31
Not for frontend component tests (use the test-react-testing-library skill instead).
- Distinctive: line 32
Does not test against real external services or databases — those must be mocked.
- Very specific: line 56
Create the module in beforeEach, not beforeAll, so every test starts isolated
- Very specific: line 62
Call jest.clearAllMocks() in afterEach
- Distinctive: line 70
Call real external services or databases from a unit test
- Very specific: line 71
Import AppModule into a unit test module
- Very specific: line 72
Leave a promise assertion without await — the test then passes unconditionally
- Very specific: line 76
Leave jest.useFakeTimers() active past the test that needed it
≈ “Common” is an estimate: at least 1 in 5 of the 350,495 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
NestJS Jest Testing Module Unit Tests
Overview
Write unit tests for NestJS applications using Test.createTestingModule and Jest.
Capabilities:
- Implement the RED phase tests of TDD.
- Scaffold isolated unit test suites with
Test.createTestingModule(...).compile()and resolve providers viamodule.get(...). - Test services, controllers, guards, interceptors, and pipes in isolation with mocked dependencies (
useValuewithjest.fn()). - Mock external services (HTTP, databases/repositories, SDKs) so tests stay fast, deterministic, and side-effect free.
- Cover edge cases: thrown exceptions (
NotFoundException,ConflictException), API timeouts, rate limiting, and time-dependent logic viajest.useFakeTimers().
Limitations:
- It does not implement production-functional code, it only implements tests.
- Not for API integration tests that exercise the full HTTP request/response cycle (use the
test-nestjs-supertestskill instead). - Not for true browser E2E tests that drive a UI (use the
playwright/cypressskills instead). - Not for frontend component tests (use the
test-react-testing-libraryskill instead). - Does not test against real external services or databases — those must be mocked.
Prerequisites
- A NestJS application with
@nestjs/testingandjestinstalled. - Providers/services under test that receive their dependencies via NestJS dependency injection (constructor injection).
- A Jest config that discovers unit test files (conventionally
*.spec.ts).
Core Workflow
- Locate the spec — co-locate
<name>.spec.tsnext to the class under test, insidesrc/. - Compile a minimal module —
Test.createTestingModule({ providers: [...] }).compile()inbeforeEach, declaring only the class under test plus its direct dependencies. - Mock every dependency —
{ provide: Token, useValue: { method: jest.fn() } }, using the right token (getRepositoryToken,getModelToken, custom@Injecttoken). - Resolve —
module.get<T>(Token)for singletons,await module.resolve<T>(Token)forREQUEST/TRANSIENTscope. - Write the happy path — arrange the stubs, act, assert the returned value and the observable side effects.
- Write the failure paths — thrown exceptions, dependency errors, timeouts, and the absence of side effects on error.
- Clean up —
jest.clearAllMocks()inafterEach;jest.useRealTimers()too when fake timers were used.
Constraints
MUST DO
- Build the module with
Test.createTestingModule(...).compile()— never instantiate the class withnew - Declare only the class under test and its direct dependencies; never import
AppModule - Create the module in
beforeEach, notbeforeAll, so every test starts isolated - Mock every external dependency: HTTP clients, repositories, message queues, SDKs
- Type mocks as
jest.Mocked<T>, or derive the type from a factory withReturnType<typeof factory> - Stub every call the method under test makes, not only the one being asserted
awaitevery promise assertion:await expect(...).rejects.toThrow(...)- Assert the returned value, not merely that a mock was called
- Call
jest.clearAllMocks()inafterEach - Restore timers with
jest.useRealTimers()inafterEachwheneverjest.useFakeTimers()was used - Return observables (
of(...)/throwError(...)) fromHttpServicemocks — not resolved promises - Cover the denial path of every guard, not just the allow path
MUST NOT DO
- Instantiate the class under test manually (
new UsersService(new UserRepository())) - Call real external services or databases from a unit test
- Import
AppModuleinto a unit test module - Leave a promise assertion without
await— the test then passes unconditionally - Ship a mock that only covers the happy path, with no error scenario
- Assert on private methods or properties (
(service as any).buildQuery) - Cast a mock with
as anyto satisfy a wide SDK interface — infer the type from the factory instead - Leave
jest.useFakeTimers()active past the test that needed it
Examples
- Service with a mocked repository — provide
UsersServiceplus auseValuemock forUserRepository, then assert thatservice.create(dto)callsrepo.save(dto)and returns the saved user. See references/test-use-testing-module.md. - Exception paths — mock
repo.findOneto return an existing record and assertservice.create(...)rejects withConflictException; mock it to returnnulland assertfindById(...)rejects withNotFoundException. - Guard testing — compile a module with
RolesGuardplus auseValuemock forReflector, stubreflector.getAllAndOverride, and assertguard.canActivate(context)returns the expected boolean. Always include the denial cases (wrong role, no user at all): a guard that always returnedtruewould pass an allow-only suite. - Mocked external HTTP service — provide a
jest.Mocked<HttpService>, returnof(mockResponse)for success andthrowError(...)for timeout/rate-limit cases. See references/test-mock-external-services.md.
References
For more details, consult these reference files (loaded on demand):
- references/test-mock-external-services.md - Mock external services in tests
- references/test-use-testing-module.md - Use Testing Module for unit tests
These files are only loaded if the agent needs additional context.
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.

