Production: security, testing and deployment · Lesson 16 of 18
Testing with assert and node:test
Test behavior quickly and separate unit from integration tests without noisy output.
A good test follows Arrange, Act, Assert and checks one clear behavior. node:assert/strict throws when an expectation fails, making it useful in scripts and exercises. node:test adds a built-in runner, subtests, hooks and TAP output without third-party packages.
Arrange input
Act
Assert behavior
Refactor confidently
const assert = require("node:assert/strict")
function total(items) {
return items.reduce((sum, item) => sum + item.price * item.qty, 0)
}
assert.equal(total([]), 0)
assert.equal(total([{ price: 5, qty: 2 }, { price: 3, qty: 1 }]), 13)
assert.throws(() => { throw new TypeError("bad input") }, TypeError)
console.log("all tests passed")A unit test isolates a fast function; an integration test checks components such as HTTP, database and files together. Do not mock so much that you only test implementation. Cover happy paths, boundaries and failures, keeping tests deterministic without real clocks or external networks.
// Save as cart.test.js and run: node --test
const test = require("node:test")
const assert = require("node:assert/strict")
test("adds two prices", () => {
assert.equal(5 + 3, 8)
})Quick question
What does an integration test check?
Exercise
Write divide(a,b) throwing RangeError when b is zero. Test 8/2 and the error, then print all tests passed.
Expected output: all tests passed
const assert = require("node:assert/strict")
function divide(a, b) {
}
assert.equal(divide(8, 2), 4)
assert.throws(() => divide(1, 0), RangeError)
console.log("all tests passed")Learn more from
Played 0 of 2 games
Sign in to save your progress and earn XP.