Sikau

Node.js · Day 15 · about 30 min

Testing with node:test

Prove your code works — and keeps working.

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.

The rest of this lesson

  • Testing an API end to endexplain
  • What to testexplain
  • Pass or fail?predict
  • An API testorder
  • Your turnwrite code
  • Badge quizquiz
  • What you learnedrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 18 lessons of Node.js