Skip to curriculum
Jump to the editor

24.1. Assertions

Easy
Topics

This question is in

24. Build a small library
15–25 min

Every test framework sits on a small layer of assertions: functions that check one fact and throw when it is false. The quality of that layer decides how fast a failure can be fixed. "AssertionError: Expected 3, got 2" points straight at the bug; "false is not true" sends you to a debugger.

Write a small assertion library in assert.js: an error class, a helper that turns values into readable text, and five assertions on an assert object.

Signature

JAVASCRIPT
class AssertionError extends Error // new AssertionError(message, actual, expected)
function format(value)             // returns a string
const assert = {
  ok(value, message),
  equal(actual, expected, message),
  notEqual(actual, expected, message),
  deepEqual(actual, expected, message),
  throws(fn, ErrorType, message),  // returns what fn threw
};
  • An assertion that holds returns undefined (throws returns the thrown value). One that fails throws an AssertionError.
  • message is optional in every assertion. When given, it replaces the default message.

Requirements

  1. new AssertionError(message, actual, expected) is an Error with name "AssertionError", that message, and the two values kept as error.actual and error.expected.
  2. format(value): strings, arrays and other non-null objects go through JSON.stringify; -0 becomes "-0"; anything else goes through String.
  3. assert.ok(value) fails for every falsy value. Default message: Expected a truthy value, got <value>.
  4. assert.equal(actual, expected) compares with Object.is: NaN equals NaN, 0 does not equal -0, two objects are equal only when they are the same object. Default message: Expected <expected>, got <actual>.
  5. assert.notEqual fails exactly when equal would pass. Default message: Expected a value other than <expected>.
  6. assert.deepEqual compares arrays and objects by content at every depth: the same own enumerable keys (in any order, as Object.keys lists them), arrays of the same length, each pair of values deep equal, and leaves compared with Object.is. An array never equals a non-array. A hole is a missing key, so [ , 1] differs from [undefined, 1], and [] differs from new Array(1). Default message: Expected <expected> (deep), got <actual>.
  7. assert.throws(fn) fails when fn returns, with the message Expected the function to throw. It counts any thrown value, undefined included.
  8. With ErrorType, the thrown value must be an instance of it (a subclass counts). Otherwise the message is Expected <type>, got <name>, where <type> is ErrorType.name and <name> is the thrown value's name property, or format(value) when it has none.
  9. assert.throws called without a function throws a TypeError with the message assert.throws expects a function (a mistake in the test, not a failed assertion).

In every message, <value>, <actual> and <expected> stand for format of that value.

Examples

JAVASCRIPT
assert.equal(2 + 2, 4);            // returns undefined
assert.equal("1", 1);              // throws AssertionError: Expected 1, got "1"
assert.equal(0, -0);               // throws AssertionError: Expected -0, got 0
assert.ok("", "name is required"); // throws AssertionError: name is required
JAVASCRIPT
assert.deepEqual({ a: [1, 2] }, { a: [1, 2] }); // passes
assert.deepEqual(["x"], { 0: "x" });
// throws AssertionError: Expected {"0":"x"} (deep), got ["x"]
JAVASCRIPT
const error = assert.throws(() => JSON.parse("{"), SyntaxError);
error.name; // "SyntaxError"

assert.throws(() => { throw new RangeError("x"); }, TypeError);
// throws AssertionError: Expected TypeError, got RangeError

Environment

  • Plain JavaScript in a browser page. The tests read the globals AssertionError, format and assert from assert.js.
  • deepEqual only needs arrays and plain objects. Map, Set, Date, prototypes and cycles are out of scope.
  • format may assume objects contain no cycles.

Hints

  1. What does Object.is decide differently from ===, and which two values show it?
  2. In throws, how do you tell "nothing was thrown" from "undefined was thrown"?

The explanation comes with the course

A walkthrough of every line of a solution, the mistakes the tests catch, other ways to write it, and links to the lessons that teach each idea.

  • Every line explained
  • The mistakes each test catches
  • Links to the lessons behind it
Back to the question
Loading the editor…