Tests protect refactors and document behavior. Node ships a built-in test runner (node --test); Jest and Vitest are popular alternatives with mocking utilities.
Test pyramid
- Unit — pure functions, validators, utils (fast, many)
- Integration — HTTP handlers with supertest, DB test containers
- E2E — full browser/API flows (fewer, slower)
node:test sketch
import { test } from 'node:test';
import assert from 'node:assert/strict';
test('adds numbers', () => {
assert.equal(1 + 2, 3);
});
What to test first
Validation functions, auth guards, and business rules before UI—high value, low setup. Mock external APIs at HTTP boundary.
Important interview questions and answers
- Q: Unit vs integration test?
A: Unit isolates one module; integration exercises real HTTP/DB layers together—slower but catches wiring bugs. - Q: How test Express routes?
A: supertest calls app without listening on a port—assert status and JSON body.
Self-check
- What command runs Node built-in tests?
- Why test validators before controllers?
Tip: Test pure functions first—they need no HTTP mock and give fast feedback before integration tests.