Node.js Built-in Test Runner
Node has a built-in test runner (node --test) and an assert module. Tests describe expected behaviour and fail loudly when the code breaks.
ExampleNode.js
const assert = require("assert");
function isPalindrome(s) {
const clean = s.toLowerCase().replace(/[^a-z0-9]/g, "");
return clean === [...clean].reverse().join("");
}
const cases = [
["racecar", true],
["A man, a plan, a canal: Panama", true],
["hello", false],
];
for (const [input, expected] of cases) {
assert.strictEqual(isPalindrome(input), expected);
console.log("pass:", input);
}
assert.deepStrictEqual({ a: [1, 2] }, { a: [1, 2] });
assert.throws(() => JSON.parse("{bad"), SyntaxError);
console.log("all assertions passed");Output
pass: racecar pass: A man, a plan, a canal: Panama pass: hello all assertions passed
In a real project, put this in isPalindrome.test.js using const test = require('node:test') and run node --test.
Quick check
What happens when an assert fails?
Finish the quick check (and any code exercise) to complete this lesson, or mark it done yourself.
Tip: use the left and right arrow keys to move between lessons.