← Learning Hub
Advanced

Testing with node:test

Tests are small programs that check your code works, so you can change it without fear. Node has a test runner built in: node:test with node:assert.

Tests check that your code does what you expect, automatically, every time you change it. Node's built-in test runner means you can start testing without installing anything. Tests for an API catch broken routes before your users do.

Example
// price.test.mjs
import { test } from "node:test";
import assert from "node:assert/strict";

function finalPrice(price, coupon) {
  if (price < 0) throw new Error("price can't be negative");
  if (!coupon) return price;
  if (coupon.type === "flat") return Math.max(0, price - coupon.amount);
  return Math.round(price * (1 - coupon.percent / 100));
}

test("no coupon keeps the price", () => {
  assert.equal(finalPrice(500), 500);
});

test("flat coupon never goes below zero", () => {
  assert.equal(finalPrice(100, { type: "flat", amount: 150 }), 0);
});

test("percent coupon rounds to whole rupees", () => {
  assert.equal(finalPrice(999, { type: "percent", percent: 15 }), 849);
});

test("negative price is an error", () => {
  assert.throws(() => finalPrice(-1), /negative/);
});

// Running it with the dot reporter prints one dot per passing test (`node --test --test-reporter=dot price.test.mjs`):
// ....

Run all tests with node --test (or npm test). The normal report lists each test with a ✔ or ✖ and how long it took.

Testing an Express API

Start the app on a random free port inside the test, then call it with fetch:

Example
// api.test.mjs
import { test, after } from "node:test";
import assert from "node:assert/strict";
import express from "express";

const app = express();
app.get("/health", (req, res) => res.json({ ok: true }));

const server = app.listen(0);                    // 0 = any free port
const base = `http://localhost:${server.address().port}`;
after(() => server.close());

test("GET /health says ok", async () => {
  const res = await fetch(base + "/health");
  assert.equal(res.status, 200);
  assert.deepEqual(await res.json(), { ok: true });
});

test("unknown route is 404", async () => {
  const res = await fetch(base + "/nope");
  assert.equal(res.status, 404);
});

// Running it with the dot reporter prints (`node --test --test-reporter=dot api.test.mjs`):
// ..
In a real project, export app from app.js and call app.listen in a separate server.js. Then tests can import the app without starting the real server. Popular alternatives: Vitest, Jest, and Supertest for APIs.
Key points
  • node:test and node:assert are built in.
  • Run tests with node --test.
  • Start the app on a random port to test APIs.

📝 Test yourself

1. Which command runs Node's built-in tests?
2. Which assert checks that two objects have the same contents?
3. Fill in the assert that expects an error:
assert.(() => finalPrice(-1));