Module P-5·23 min read

Unit testing with Jest, integration testing with Supertest, mocking modules, database testing strategies, meaningful coverage, and CI integration.

JJS
Written by Jatin Jain Saraf · Senior Software Engineer

Module P-5 — Testing Node.js Applications

What this module covers: Untested code is a liability — you cannot refactor it safely, you cannot ship it confidently, and you cannot onboard a new engineer without fear. This module covers the testing pyramid for Node.js: unit tests with Jest that test one function in isolation, integration tests with Supertest that hit real Express routes, the correct way to mock dependencies so tests stay fast and deterministic, database testing strategies, and wiring tests into CI. By the end you will have a test suite that actually catches bugs and runs in seconds.


The Testing Pyramid

Three levels of tests, each with a different trade-off:

text
  • Unit tests: Test a single function — a service method, a validator, a utility. No HTTP, no database, no network. Run in milliseconds.
  • Integration tests: Test an Express route from HTTP request to HTTP response. Real validation middleware, real service logic, but the database layer is mocked or uses a test database.
  • End-to-end tests: Spin up the full stack against a real database. Slow and brittle. Write few, keep them for critical paths only.

For a Node.js API, the sweet spot is: many unit tests for service/business logic, integration tests for every route, minimal E2E tests.


Setup: Jest and Supertest

bash
json

Note that jest.config.ts requires ts-node on top of ts-jest — they do different jobs. ts-jest transforms your .test.ts files at test-run time; Jest's own config loader needs ts-node to parse jest.config.ts itself, before any tests run. Skip the ts-node install and Jest fails immediately trying to load its own config, before a single test executes.

json

Unit Testing: Services

Services contain the business logic — test them thoroughly. They take plain inputs and return plain outputs. No HTTP to set up.

typescript

Notice the pattern: set up mocks, call the function, assert on the output or thrown error. Each test describes one behaviour. The test names read like a specification.


Unit Testing: Validators

Schemas are pure functions — trivial to test:

typescript

Testing Time-Dependent Code

Sign in to keep reading

The rest of this module is free — sign in with Google to unlock it and track your progress.

Sign in & Register

Discussion

0

Join the discussion

Loading comments...

© 2026 Jatin Jain Saraf (JJS). All rights reserved.