Hone

Lessons · JavaScript · assert

assert says what must be true

node's assert throws an AssertionError with your message when a claim fails and does nothing when it holds. It is a sentence about your code that the computer checks.

Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.

What it is for

Every challenge on Hone is graded by claims like these. Knowing what one says, and what its silence means, is how you read a failing test instead of fearing it.

How to think about it

Write the claim as you would say it: 'the total is 7'. Put the expected value second. Give a message that says what was expected. Use deepStrictEqual for arrays and objects, strictEqual for everything else.

Worked example

const assert = require('assert');
node's assert: throws when a claim fails.
function add(a, b) { return a + b; }
assert.strictEqual(add(2, 3), 5);
Holds: nothing happens.
try {
  assert.strictEqual(add(2, 2), 5, 'expected 5');
Does not hold: throws, with the message.
} catch (e) { console.log('failed:', e.message.split('\n')[0]); }
failed: expected 5 (node adds its own diff below the message)
console.log('done');
done

Your turn

Compare two arrays by their contents.

assert.([1, 2], result);

The trap

assert.strictEqual on two arrays. They are two objects, so it fails even when the contents match; deepStrictEqual is the one you meant.

Practise assert on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.