Build ok, equal, notEqual, and throws assertion helpers
A team writes quick self-checks inside build scripts and does not want to pull in a full test framework for them. Build a tiny assertion library: four checks that do nothing when they pass and throw a descriptive error when they fail.
Implement an object named tinyAssert:
tinyAssert.ok(value, message?)
tinyAssert.equal(actual, expected, message?)
tinyAssert.notEqual(actual, expected, message?)
tinyAssert.throws(fn, matcher?, message?) // => the thrown value
tinyAssert.AssertionError // the error class
ok(value) passes when value is truthy.equal(actual, expected) passes when Object.is(actual, expected). So NaN equals NaN, 0 does not equal -0, 1 does not equal '1', and objects are equal only if they are the same reference.notEqual(actual, expected) passes when equal would fail.throws(fn, matcher) calls fn() with no arguments. It fails if fn does not throw. If it throws, the thrown value must match matcher:
undefined: anything matches.RangeError): matches if thrown instanceof matcher.RegExp: matches if it tests true against the thrown message.The thrown message is thrown.message when the thrown value is an object with a string message, and String(thrown) otherwise. When the check passes, throws returns the thrown value.
undefined (except throws) and have no side effects.A failing check throws a tinyAssert.AssertionError. It extends Error, has name set to 'AssertionError', and has these properties:
| Check | operator |
actual |
expected |
Default message |
|---|---|---|---|---|
ok |
'ok' |
the value | true |
Expected <value> to be truthy |
equal |
'equal' |
actual | expected | Expected <actual> to equal <expected> |
notEqual |
'notEqual' |
actual | expected | Expected <actual> not to equal <expected> |
throws, nothing thrown |
'throws' |
undefined |
the matcher | Expected function to throw |
throws, no match |
'throws' |
the thrown value | the matcher | Thrown error did not match |
Values inside default messages are formatted like this:
JSON.stringify, so '1' becomes "1" (with the double quotes).-0 becomes -0, and bigints get an n suffix (10n).String(value): NaN, null, undefined, true, Symbol(id).String(Object.create(null)) throws, and so does a template literal with a symbol inside.message replaces the default message. All other properties stay the same.message is an Error instance, a failing check throws that error itself instead of an AssertionError.tinyAssert.ok(cart.items.length); // passes when the cart is not empty
tinyAssert.equal(total, 42);
tinyAssert.equal(1, '1');
// AssertionError: Expected 1 to equal "1"
tinyAssert.equal(NaN, NaN); // passes
tinyAssert.notEqual(0, -0); // passes
const error = tinyAssert.throws(() => parseConfig(''), /empty/);
error.message; // => 'Config is empty'
tinyAssert.throws(() => {}, undefined, 'parseConfig should reject empty input');
// AssertionError: parseConfig should reject empty input