bhylu.com

Advertisements

Node.js Assertions

An assertion states what must be true for a fixture. Good tests check both intended results and the inputs the domain must reject.

How it works

Node’s strict assertion module works without an extra package. Compare the result you care about rather than mirroring each line of the implementation. This small quantity function has boundaries at one and twenty, so the example checks those accepted endpoints and rejects zero and fractional input. A passing test set only covers its cases; it is not proof that every possible program path is correct.

Run the code

Run this example locally with Node.js. The exact sources are reviewed on Node 22.15.1 and Node 24.22.1 unless a specialised lab states otherwise. Save the complete source as assertions.mjs in a separate empty exercises folder and run node assertions.mjs. There is no Node.js browser runner on Bhylu; the plain JavaScript playground does not provide these filesystem, server or process APIs.

Download the complete source. Ordinary Node scripts need no Apache, PHP or MySQL service. File examples own their temporary folders; network fixtures use loopback and available temporary ports.

Example

assertions.mjs

import assert from 'node:assert/strict';
export function quantity(value) {
  if (!Number.isInteger(value) || value < 1 || value > 20)
    throw new RangeError('Invalid quantity');
  return value;
}
assert.equal(quantity(1), 1);
assert.equal(quantity(20), 20);
assert.throws(() => quantity(0), RangeError);
assert.throws(() => quantity(1.5), RangeError);
console.log('Four boundary assertions passed');

Expected result

Four boundary assertions passed

The tests state the accepted endpoints and representative rejected values. Additional callers can use the same exported helper in their own tests. Real input parsing may need to distinguish a text quantity from an already validated numeric value before reaching it.

Use the Node.js API reference for the precise version contract.