Node.js Testing

Testing protects your Node code from regressions. Keep tests close to behavior and run them often.

Checks

Modern Node.js ships with a built-in test runner (node:test) and strict assertions (node:assert/strict), so you can write unit and HTTP integration tests without installing external frameworks. Focus on verifying observable behavior rather than internal implementation details:

  • Pure functions: Assert that given inputs produce expected outputs and edge cases throw clear errors.
  • HTTP routes: Test status codes, Content-Type headers, and JSON error bodies against your handler.
  • Async paths: Verify rejected Promises and timeouts as well as happy-path responses.
import test from "node:test";
import assert from "node:assert/strict";

function sum(a, b) {
  return a + b;
}

test("sum adds positive and negative numbers", () => {
  assert.equal(sum(2, 3), 5);
  assert.equal(sum(-1, 1), 0);
});

Package scripts

Wire node --test into package.json so every developer and CI job runs the exact same test command. Node automatically discovers files matching *.test.js or *.test.mjs:

{
  "scripts": {
    "test": "node --test"
  }
}

Practice

Verify the red-green-refactor cycle locally with Node's built-in runner:

  1. Create math.test.mjs using node:test and node:assert/strict and run npm test.
  2. Intentionally break an assertion to confirm the failure output pinpoints the line, then fix it.
  3. Write an async test that verifies an error is rejected with assert.rejects().