Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

Testing and assertions

A test compares observed behavior with an expectation, and an assertion signals when a condition is not met. See a small unit test using a built-in Node.js module and learn why comparison rules and boundary cases matter.

Version: Syntax snippet: Requires ECMAScript 2015 or later because it uses Object.is, which was standardized in ECMAScript 2015. Executable example: verified in Node.js 24.22.2 using the built-in node:assert/strict module. This does not establish browser API support.

Syntax

function assertEqual(actual, expected, label) {
  if (!Object.is(actual, expected)) {
    throw new Error(label);
  }
}

A test checks program behavior for specified inputs and expectations. A failed assertion means the test has failed. In a unit test, focus on a small unit such as a function: set up the inputs, call the function, and check the result. Merely avoiding an exception does not establish that the result is correct.

The syntax snippet defines a custom function, assertEqual. It uses Object.is and executes throw new Error(label) on a mismatch. Object.is treats NaN as equal to NaN, distinguishes +0 from -0, and compares objects by identity rather than by contents. It is not a deep comparison.

The runnable example does not use assertEqual. It imports Node.js’s built-in node:assert/strict module and calls assert.equal, which in this mode compares values using the rules of Object.is. The three assertions check the sum of two positive numbers, the sum of two opposite numbers, and the string "0.3" produced by formatting the sum 0.1 + 0.2 with toFixed(1). The last assertion compares a string, not the raw numeric result. An uncaught assertion error stops the script before it prints the success message.

Choose both ordinary inputs and boundary cases from the function’s contract. Determine expectations independently of the implementation under test. To check the test itself, deliberately change one expectation and confirm that the assertion fails. Passing these cases does not prove correctness for every input.

The syntax snippet uses language features available since ECMAScript 2015 or earlier and described in the ECMAScript specification. The assertion API is described in the Node.js documentation. The example requires Node.js but does not need browser APIs or a third-party library. Having Node 24 in a repository does not establish browser API support.

Examples

import assert from "node:assert/strict";

const add = (left, right) => left + right;
assert.equal(add(2, 3), 5);
assert.equal(add(-1, 1), 0);
assert.equal(add(0.1, 0.2).toFixed(1), "0.3");
console.log("3 assertions passed");

Result

3 assertions passed

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources