JavaScript: unit tests with node:assert

A unit test calls a function with known input and asserts the expected result. Node.js includes the assert module, and node:test is its built-in test runner. The strict mode of assert compares with ===, which avoids the surprises of loose equality.

JavaScript
const assert = require("node:assert/strict");

function percent(text) {
  const n = Number(text);
  if (text.trim() === "" || !Number.isInteger(n) || n < 0 || n > 100) {
    throw new RangeError("invalid percent: " + text);
  }
  return n;
}

let failures = 0;
function test(name, fn) {
  try {
    fn();
    console.log("PASS " + name);
  } catch (error) {
    failures++;
    console.log("FAIL " + name + ": " + error.message);
  }
}

test("parses 42", () => assert.equal(percent("42"), 42));
test("accepts the boundary 100", () => assert.equal(percent("100"), 100));
test("rejects 101", () => assert.throws(() => percent("101"), RangeError));
test("rejects an empty string", () => assert.throws(() => percent("")));
test("reports the bad text", () => assert.throws(() => percent("abc"), { message: "invalid percent: abc" }));
console.log("failures: " + failures);
Read the full lesson