Course progress0%
Course content

Module 1

Module 2

Module 3

Module 4

Module 5

Module 6

Module 7

Module 8

Module 9

Module 10

Module 11

Module 12

Module 13

Module 14

Module 15

Module 16

Module 17

Module 18

35 min

Basic Assertions and a Failing Test Run

Make a test failure observable

By the end of this lesson

  • Make a test failure observable
  • Use strict assertions in a file-based test script

A logged failure is not always a failed run

Console.assert is convenient in the browser, but normally logs a failure without throwing or stopping execution. For a test script, a thrown assertion gives a clearer failure signal.

function assertEqual(actual, expected, message) {
  if (actual !== expected) {
    throw new Error(`${message}: expected ${expected}, received ${actual}`);
  }
}
function calculateSubtotal(price, quantity) {
  return price * quantity;
}
assertEqual(calculateSubtotal(20, 3), 60, "Subtotal for three items");
assertEqual(calculateSubtotal(20, 1), 20, "Subtotal for one item");

This helper compares primitive values using strict equality. It does not deeply compare arrays or objects. Keep test messages specific enough to identify the requirement that failed.

A built-in option for file-based projects

In the Node .mjs setup from module 13, create checks.mjs:

import assert from "node:assert/strict";
assert.equal(20 * 3, 60);
assert.deepEqual([20, 40], [20, 40]);
assert.throws(() => { throw new Error("Invalid quantity"); }, /Invalid quantity/);
console.log("Checks passed");

Run node checks.mjs. Node's built-in assertion module requires no package installation. DeepEqual compares structured values. Throws runs the supplied function and checks its thrown error. The slashes delimit a regular expression used here to match the message.

Independent exercise

Put one deliberately wrong expected result in a private copy of the test script. Run it, read the failure, then restore the correct expectation. Explain why this experiment is useful and why the wrong expectation must not remain in the final script.

Correction

It demonstrates that your checking mechanism can actually detect a mismatch. A test script that always prints success despite failing checks is misleading. After restoration, the expectations must come from the requirements, not from whatever makes the run green.

Review

For the final project, use Node assertions and an explicit test command. A larger framework can improve organization later, but the essential skill is selecting meaningful cases and recognizing failure.

Lesson complete?

Your progress is saved on this device.