Write isolated unit and HTTP tests with node:test, strict assertions, mocks, coverage reporting, deterministic cleanup, and a CI-friendly exit status.
What you will build
This tutorial produces a working, verifiable result rather than a command list. Read each command before running it, keep configuration in version control without secrets, and record the versions used for repeatable deployment.
1. Prepare the project
npm pkg set scripts.test='node --test' scripts.coverage='node --test --experimental-test-coverage'
mkdir -p test src
Run preparation commands as an unprivileged application user unless a command explicitly requires sudo. A clean working tree and lockfile make rollback much easier.
2. Implement the solution
// src/math.js
export const divide=(a,b)=>{if(b===0) throw new RangeError('division by zero'); return a/b;};
// test/math.test.js
import test from 'node:test'; import assert from 'node:assert/strict'; import {divide} from '../src/math.js';
test('divides two numbers',()=>assert.equal(divide(8,2),4));
test('rejects division by zero',()=>assert.throws(()=>divide(1,0),RangeError));
test('temporary resource',{timeout:1000},async t=>{const resource={close:()=>{}}; t.after(()=>resource.close()); assert.ok(resource);});
Save the example in the filename indicated by its comment or surrounding instructions. Treat it as a minimal baseline: production applications should separate transport, business logic, persistence, and configuration into testable modules.
3. Verify end to end
npm test
npm run coverage
node --test --test-name-pattern='divides'
Verification should cover both process state and a real request or data operation. A process that is merely running is not necessarily ready to serve traffic.
4. Troubleshooting and production notes
Tests must close servers, database pools, timers, and sockets or the process can hang. Avoid sharing mutable state across test files. Use a separate database and never point integration cleanup at production credentials.
Production checklist
- The supported Node.js LTS version and dependency lockfile are recorded.
- Configuration is validated at startup and secrets are stored outside source control.
- Input limits, authentication, authorization, timeouts, and error boundaries are explicit.
- Logs identify a request without exposing credentials or personal data.
- Health checks, graceful termination, resource limits, backup, and rollback have been tested.
Reference: official topic documentation. For production version selection, use a supported LTS line from the Node.js release schedule.