Change code without fear
Every time you change code, something else might break. Tests check behaviour automatically in seconds. Node has a built-in test runner: node --test.
test, describe and assert
import { describe, test } from "node:test";
import assert from "node:assert/strict";
import { orderTotal } from "./lib/orders.js";
describe("orderTotal", () => {
test("adds prices times quantities", () => {
assert.equal(orderTotal([{ price: 180, qty: 2 }, { price: 60, qty: 1 }]), 420);
});
test("an empty order costs 0", () => {
assert.equal(orderTotal([]), 0);
});
test("rejects negative quantities", () => {
assert.throws(() => orderTotal([{ price: 100, qty: -1 }]));
});
});- Run with node --test (it finds *.test.js files). Many teams use Vitest or Jest — same ideas.
- Test HTTP APIs by starting the app and calling it with fetch (as you've been doing!), or with Supertest.
- Fix a bug? First write a test that fails because of it — then it can never quietly come back.