Skip to content
NestPath

Exercises — Testing (Unit + E2E)

Covers: unit (.spec.ts) vs E2E (.e2e-spec.ts) and which to write when, Jest + Supertest stack, jest configs (package.json unit config, test/jest-e2e.json) and npm scripts, Test.createTestingModule mini-DI-container, mocking: getModelToken, jest.fn() / .mockReturnValue / .mockResolvedValue(Once), Mongoose chain mocks (find().exec()), jest.mock('bcrypt'), jest.clearAllMocks(), rejects.toThrow, expect.objectContaining, toHaveBeenNthCalledWith, mocking ExecutionContext for guards, testing interceptors with fake CallHandler/of(), E2E: MongoMemoryServer, real AppModule, re-registering global pipes/filters/interceptors/cookie-parser in createTestApp, supertest requests, sequential story-style describe blocks with shared state, coverage/watch/pattern run commands, the unit-vs-E2E bug-catching matrix, the testing decision framework.


Part A — Concept Checks (closed book)

  1. Unit vs E2E: what does each spin up, what does each mock, and what's the file-naming convention for each?
  2. "Which to write first?" — what does the lesson recommend and what's the reasoning about feedback speed vs wiring confidence?
  3. Recite the 4-step unit-test mental model.
  4. What is Test.createTestingModule() — what does "mini DI container" mean in practice?
  5. Why does testing TasksService require getModelToken(Task.name)? What are you actually swapping?
  6. Why must Mongoose mocks be chain-shaped (find returns { exec: jest.fn() }) rather than resolving directly?
  7. What bug class does forgetting jest.clearAllMocks() create? Where does it belong in the file?
  8. Why jest.mock('bcrypt') at module level — what's the performance argument with numbers from the lesson?
  9. .mockResolvedValueOnce() vs .mockResolvedValue() — which does the AuthService token test need and why (two signAsync calls)?
  10. What do expect.objectContaining and toHaveBeenNthCalledWith each verify in the token-signing test, and which security design decision does the Nth-call assertion protect?
  11. Why must guards be tested with a hand-built fake ExecutionContext? Which three methods must the fake implement?
  12. rejects.toThrow — what happens to the test if you forget rejects on an async throw?
  13. Why MongoMemoryServer? Three problems it solves.
  14. Why do E2E tests import the real AppModule, and name two bug classes only that choice catches.
  15. Why must createTestApp re-register ValidationPipe, filters, interceptors, and cookie-parser? (You've met this in Module 02 D3.)
  16. Why write the E2E auth flow as sequential steps in one describe block with shared variables? What Jest behavior makes it safe?
  17. From the bug-matrix: name three bugs only E2E catches and one where unit is the better (faster) tool.
  18. The decision framework: which test type for (a) refresh-token reuse detection logic, (b) "guard actually applied to DELETE route", (c) a pure date-format util?

Part B — Guided Exercises

B1. Configs and first run

  1. Verify/add jest config in package.json (unit) and test/jest-e2e.json. Add scripts: test, test:watch, test:cov, test:e2e.
  2. Run npm test on the CLI-generated specs. Then run npm run test:cov and read the coverage table — identify your least-covered file.

B2. Unit: TasksService (Mongo-backed, from Module 07)

Write tasks.service.spec.ts: 1. Mock the model via getModelToken(Task.name) with find/findById/create/findByIdAndUpdate/findByIdAndDelete as chainable jest mocks. 2. Tests: findAll returns the mocked array; findOne returns a task; findOne rejects with NotFoundException for null; create calls the model with ownerId stamped from the user; update ownership: owner may update, non-owner non-admin rejects with ForbiddenException, admin may update someone else's. 3. beforeEach with jest.clearAllMocks(). Prove its worth: comment it out, reorder two tests, watch something leak (or explain why it would).

B3. Unit: AuthService

  1. jest.mock('bcrypt'). Mock UsersService, JwtService, ConfigService.
  2. Tests: register hashes with 12 rounds (toHaveBeenCalledWith(password, 12)) and returns no tokens; login with unknown email AND wrong password both reject with the same UnauthorizedException (two tests, same assertion — enumeration safety encoded as a test); login signs two tokens — use mockResolvedValueOnce twice and toHaveBeenNthCalledWith to assert the full payload on call 1 and minimal { sub } payload on call 2; refresh with a rotated-out token rejects and calls removeAllRefreshTokens (reuse detection as a test!).

B4. Unit: AuthGuard + TransformInterceptor

  1. Build a mockExecutionContext(headers, isPublic) helper: switchToHttp().getRequest(), getHandler(), getClass(); mock Reflector.getAllAndOverride.
  2. Guard tests: public route passes with no token; missing token → UnauthorizedException; malformed header (Token abc) → 401; valid verify → returns true AND attaches request.user.
  3. Interceptor test: fake CallHandler { handle: () => of({ id: 1 }) }, subscribe to the result, assert the envelope { success: true, data: { id: 1 }, timestamp, path }.

B5. E2E: the full story

  1. Create test/setup.ts (createTestApp/closeTestApp) with MongoMemoryServer + env overrides + the global layers.
  2. auth.e2e-spec.ts: register (201) → duplicate register (409, envelope success:false) → login (200, accessToken present, set-cookie contains refreshToken + HttpOnly) → bad password (401 "Invalid credentials") → refresh with cookie (new token) → replay old cookie (403) → logout → refresh after logout (401/403).
  3. tasks.e2e-spec.ts: unauthenticated POST → 401; authenticated CRUD happy path asserting the envelope at each step; validation failure → 400 with details array; user B cannot PATCH user A's task → 403; admin can DELETE → 200.
  4. Confirm your suite is order-dependent on purpose: shared accessToken/taskId variables, story-style.

Part C — Independent Challenges

C1. Regression harness for every module

Convert the six guard scenarios from Module 05's checkpoint table into one E2E describe block — your permanent auth regression suite.

C2. Test the RolesGuard in isolation

Unit test with the fake ExecutionContext: no @Roles metadata → true; roles required + user has one → true; user lacks all → ForbiddenException with the exact Requires one of [admin] roles message; no user attached → the defensive branch.

C3. Break-it drills (mutation testing by hand)

Introduce each bug below, run the suites, and record which layer of tests caught it (compare against the lesson's matrix): 1. Remove @Injectable() from TasksService. 2. Delete whitelist: true from the test app's pipe. 3. Swap the APP_GUARD order (Roles before Auth). 4. Make validateToken verify with the refresh secret. 5. Change bcrypt rounds from 12 to 1. Which bugs did NOTHING catch? Write the missing test.

C4. Coverage target

Get common/ (guards, interceptors, filters) to ≥90% line coverage. The uncovered lines will teach you which branches you never exercised (e.g., the filter's string-response branch).


Part D — Debug Drills

D1

ts
mockTaskModel.find.mockResolvedValue([task]);

Test fails: service.findAll is not returning... TypeError: this.taskModel.find(...).exec is not a function. Fix the mock shape.

D2

ts
it('throws NotFoundException', async () => {
  mockModel.findById.mockReturnValue({ exec: jest.fn().mockResolvedValue(null) });
  expect(service.findOne('bad-id')).rejects.toThrow(NotFoundException);
});

The test passes even when the service is broken. What keyword is missing and what does Jest do with un-awaited rejection assertions?

D3

Test 1 asserts create was called once. Test 2, run after, asserts the same and fails with "called 2 times". Diagnose.

D4

E2E suite: every request returns raw data with no { success, data } envelope, and invalid bodies reach the controller. AppModule is imported. What did createTestApp forget, and why doesn't main.ts save you?

D5

ts
afterAll(async () => { await app.close(); });

Jest prints "A worker process has failed to exit gracefully" — tests pass but hang. What second teardown call is missing?

D6

An E2E login test asserts res.body.accessToken and fails; console.log(res.body) shows { success: true, data: { accessToken: ... } }. Not a bug — what did the author forget about their own architecture?

D7

jest.mock('bcrypt') is present, but bcrypt.compare returns undefined and login tests fail with confusing 401s. What must you still do after module-mocking, per test?


Part E — Prediction Drills

  1. Unit suite only: you delete TasksModule from AppModule.imports. Green or red? What about E2E?
  2. E2E: MongoMemoryServer per suite — do documents created in auth.e2e-spec.ts exist during tasks.e2e-spec.ts? What does your tasks suite therefore need in its beforeAll?
  3. A unit test for the guard where getAllAndOverride mock returns true (public) but no auth header is present — pass or throw?
  4. npm test — do .e2e-spec.ts files run? Why/why not (config-level answer)?
  5. You assert expect(signAsync).toHaveBeenNthCalledWith(2, { sub: userId }, expect.objectContaining({ secret: refreshSecret })) and someone "optimizes" the refresh payload to include email. What happens and why is that failure good?

Part F — Stretch Goals

  1. Controller unit tests: mock the service this time and assert delegation — then argue whether thin controllers deserve unit tests at all.
  2. Add a GitHub Actions workflow: npm ci && npm test && npm run test:e2e.
  3. Research @golevelup/ts-jest's createMock to kill hand-rolled ExecutionContext fakes.
  4. Try Stryker (mutation testing) on auth.service.ts and compare with your C3 manual mutations.

Self-Assessment Checklist

  • I can scaffold a unit test (createTestingModule + mocked providers) from memory
  • I can mock: Mongoose model chains, bcrypt, JwtService, Reflector, ExecutionContext
  • I use rejects.toThrow, objectContaining, NthCalledWith deliberately, not by copy-paste
  • My E2E setup boots the real AppModule + memory Mongo + all global layers
  • My E2E suites tell user-journey stories including rotation replay and role denial
  • Given any bug, I can say which test type catches it via the matrix

Answers & Hints

A1: Unit: one class in a mini DI container, all dependencies mocked; .spec.ts beside the source. E2E: full app + real HTTP via supertest + real (in-memory) DB; .e2e-spec.ts in test/.

A2: Unit first for logic you're actively writing (fast feedback loop); E2E to lock the wiring/journeys before shipping. Both, different jobs.

A3: Create testing module with mocked deps → get the unit from the module → call methods → assert.

A4: A DI container built for the test containing ONLY the providers you register — no HTTP, no DB, no unrelated modules.

A5: @InjectModel(Task.name) resolves via an internal token; getModelToken reproduces it so your fake model is injected instead of a real Mongoose model.

A6: Mongoose returns query builders; the service calls .exec() (or awaits a thenable). The mock must mirror the call chain the code actually makes.

A7: Cross-test state leakage — call counts and queued values persist, tests pass/fail depending on order. beforeEach(() => jest.clearAllMocks()).

A8: Real bcrypt at 12 rounds ≈ 250ms/call; ~20 tests ≈ 5 wasted seconds — and you'd be testing bcrypt, not your logic.

A9: Once — signAsync is called twice with different expected outputs (access, then refresh); Once queues per-call values.

A10: objectContaining: partial match on sign options (e.g., correct secret/expiry without matching everything). NthCalledWith: call 1 got full payload, call 2 got minimal { sub } — protecting the minimal-refresh-payload security decision.

A11: No real request exists in a unit test; fake must provide switchToHttp().getRequest(), getHandler(), getClass() (plus a mocked Reflector alongside).

A12: The rejection escapes the assertion → unhandled promise rejection / false pass; await expect(...).rejects.toThrow(...) captures it properly.

A13: No local MongoDB requirement, no dev-DB pollution, no cleanup — fresh in-memory instance per suite, torn down after.

A14: It exercises production wiring. Catches: missing module imports/exports, guards not applied, pipes/interceptors not configured, DTO decorator omissions — anything the mini-container can't see.

A15: Global layers registered in main.ts don't exist in tests because main.ts never runs; createNestApplication() starts bare. Re-register (or move them to APP_* providers so they ride along with AppModule).

A16: It's a user journey where later steps need earlier state (tokens, ids); Jest runs tests in a describe block in declaration order, so shared variables safely carry the "session".

A17: E2E-only: missing module import, guard not applied, cookie not set, DTO missing decorator, CORS, real bcrypt/DB behavior. Unit-better: intricate business-logic edge cases (fast iteration).

A18: (a) unit (service logic) — plus an E2E replay for confidence; (b) E2E; (c) plain unit test, no testing module needed.

D1: find must return a chainable: mockTaskModel.find.mockReturnValue({ exec: jest.fn().mockResolvedValue([task]) }).

D2: Missing await before expect(...). Un-awaited, the assertion is a floating promise — Jest may report pass before the rejection resolves.

D3: No jest.clearAllMocks() between tests — call counts accumulated across tests.

D4: It never re-registered the global pipe/interceptor/filter/cookie-parser on the test app; main.ts bootstrap code doesn't execute under Test.createTestingModule.

D5: await mongod.stop() — the in-memory MongoDB process keeps the event loop alive.

D6: The TransformInterceptor envelope — their own Module 04 work. Assert res.body.data.accessToken.

D7: Configure return values: (bcrypt.compare as jest.Mock).mockResolvedValue(true) (auto-mocked fns return undefined by default).

E1: Unit stays green (it never touches AppModule). E2E goes red immediately — exactly the wiring class of bug it exists for.

E2: No — each suite boots its own fresh MongoMemoryServer. The tasks suite must register+login its own users in beforeAll to obtain tokens.

E3: Pass/return true — the public check short-circuits before token extraction.

E4: No — the unit jest config's testRegex/roots target .spec.ts under src; e2e files run only under the separate jest-e2e.json config via test:e2e.

E5: The Nth-call assertion fails loudly. Good failure: the test guards a security property (minimal refresh payload); the "optimization" widened token exposure and the suite said no.