assert
- Node.js course
- Intermediate
- Lesson 83/116
- 5 min
Learn assertions with assert.
The assert module
The assert module decides whether a test passes or fails. Import it with require("node:assert"). The most common method is assert.equal(actual, expected); it throws if the two values are not equal.
Example: assert.equal(1 + 1, 2) passes (returns nothing). assert.equal(1 + 1, 3) throws AssertionError, so the test fails. assert.strictEqual is stricter; it also checks the type (e.g. "5" and 5 differ). Assertions are stacked inside a test; if any one fails the test stops.
Checking thrown errors
A function may be expected to throw an error. assert.throws(fn) takes a callback and passes if it throws; fails if it does not.
Example: assert.throws(() => { throw new Error("boom"); }) passes. assert.throws(() => { /* silent */ }) fails. You can also specify an error class: assert.throws(fn, /boom/) accepts only errors whose message matches the /boom/ pattern. This is the standard way to test functions that throw on invalid input. Combined with the test() from the previous lesson you get a full test.
Practice Write the add test
Import test from node:test and assert. Define a function add: function add(a, b) { return a + b; }. Write a test with test("add", () => { assert.equal(add(2, 3), 5); }). Print "Assertion ran" with console.log.
Starter code
// Import test and assert
// write here
// Define the add function
// write here
// Test and assertion
// write here
// Print "Assertion ran"
// write hereSample solution
const { test } = require("node:test");
const assert = require("node:assert");
function add(a, b) { return a + b; }
test("add", () => {
assert.equal(add(2, 3), 5);
});
console.log("Assertion ran");Expected output
İddia çalıştı
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the equal call
assert.____(topla(2, 3), 5);
assert.equal(topla(2, 3), 5);
Explanation: equal compares two values.
2 Match each method to its behavior
| Term | Meaning |
|---|---|
equal |
Compares two values |
strictEqual |
Strict compare with type |
throws |
Expects an error to throw |
ok |
Checks truthiness |
3 When does assert.throws(fn) fail?
assert.throws(() => {})- fn her zaman
- Never
- When fn throws
- When fn doesn't throw Correct answer
Explanation: If fn returns silently, throws fails.