Please support this book: buy it or donate

8. Assertion API



8.1. Assertions in software development

In software development, assertions state facts about values or pieces of code that must be true. If they aren’t, an exception is thrown. Node.js supports assertions via its built-in module assert. For example:

  1. import {strict as assert} from 'assert';
  2. assert.equal(3 + 5, 8);

This assertion states that the expected result of 3 plus 5 is 8. The import statement uses the recommended strict version of assert.

8.2. How assertions are used in this book

In this book, assertions are used in two ways: to document results in code examples and to implement test-driven exercises.

8.2.1. Documenting results in code examples via assertions

In code examples, assertions express expected results. Take, for example, the following function:

  1. function id(x) {
  2. return x;
  3. }

id() returns its parameter. We can show it in action via an assertion:

  1. assert.equal(id('abc'), 'abc');

In the examples, I usually omit the statement for importing assert.

The motivation behind using assertions is:

  • You can specify precisely what is expected.
  • Code examples can be tested automatically, which ensures that they really work.

8.2.2. Implementing test-driven exercises via assertions

The exercises for this book are test-driven, via the test framework mocha. Checks inside the tests are made via methods of assert.

The following is an example of such a test:

  1. // For the exercise, you must implement the function hello().
  2. // The test checks if you have done it properly.
  3. test('First exercise', () => {
  4. assert.equal(hello('world'), 'Hello world!');
  5. assert.equal(hello('Jane'), 'Hello Jane!');
  6. assert.equal(hello('John'), 'Hello John!');
  7. assert.equal(hello(''), 'Hello !');
  8. });

For more information, consult the chapter on quizzes and exercises.

8.3. Normal comparison vs. deep comparison

The strict equal() uses === to compare values. Therefore, an object is only equal to itself – even if another object has the same content (because === does not compare the contents of objects, only their identities):

  1. assert.notEqual({foo: 1}, {foo: 1});

deepEqual() is a better choice for comparing objects:

  1. assert.deepEqual({foo: 1}, {foo: 1});

This method works for Arrays, too:

  1. assert.notEqual(['a', 'b', 'c'], ['a', 'b', 'c']);
  2. assert.deepEqual(['a', 'b', 'c'], ['a', 'b', 'c']);

8.4. Quick reference: module assert

For the full documentation, see the Node.js docs.

8.4.1. Normal equality

  • function equal(actual: any, expected: any, message?: string): void

actual === expected must be true. If not, an AssertionError is thrown.

  1. assert.equal(3+3, 6);
  • function notEqual(actual: any, expected: any, message?: string): void

actual !== expected must be true. If not, an AssertionError is thrown.

  1. assert.notEqual(3+3, 22);

The optional last parameter message can be used to explain what is asserted. If the assertion fails, the message is used to set up the AssertionError that is thrown.

  1. let e;
  2. try {
  3. const x = 3;
  4. assert.equal(x, 8, 'x must be equal to 8')
  5. } catch (err) {
  6. assert.equal(String(err), 'AssertionError [ERR_ASSERTION]: x must be equal to 8');
  7. }

8.4.2. Deep equality

  • function deepEqual(actual: any, expected: any, message?: string): void

actual must be deeply equal to expected. If not, an AssertionError is thrown.

  1. assert.deepEqual([1,2,3], [1,2,3]);
  2. assert.deepEqual([], []);
  3. // To .equal(), an object is only equal to itself:
  4. assert.notEqual([], []);
  • function notDeepEqual(actual: any, expected: any, message?: string): void

actual must not be deeply equal to expected. If it is, an AssertionError is thrown.

  1. assert.notDeepEqual([1,2,3], [1,2]);

8.4.3. Expecting exceptions

If you want to (or expect to) receive an exception, you need throws(): This function calls its first parameter, the function block, and only succeeds if it throws an exception. Additional parameters can be used to specify what that exception must look like.

  • function throws(block: Function, message?: string): void
  1. assert.throws(
  2. () => {
  3. null.prop;
  4. }
  5. );
  • function throws(block: Function, error: Function, message?: string): void
  1. assert.throws(
  2. () => {
  3. null.prop;
  4. },
  5. TypeError
  6. );
  • function throws(block: Function, error: RegExp, message?: string): void
  1. assert.throws(
  2. () => {
  3. null.prop;
  4. },
  5. /^TypeError: Cannot read property 'prop' of null$/
  6. );
  • function throws(block: Function, error: Object, message?: string): void
  1. assert.throws(
  2. () => {
  3. null.prop;
  4. },
  5. {
  6. name: 'TypeError',
  7. message: `Cannot read property 'prop' of null`,
  8. }
  9. );

8.4.4. Another tool function

  • function fail(message: string | Error): never

Always throws an AssertionError when it is called. That is occasionally useful for unit testing.

  1. try {
  2. functionThatShouldThrow();
  3. assert.fail();
  4. } catch (_) {
  5. // Success
  6. }