Wizard

Assertion API • JavaScript for impatient programmers (beta)

原文链接: exploringjs.com

(Ad, please don’t block.)

7. Assertion API

7.1. Assertions in software development

In software development, assertions make statements 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:

import {strict as assert} from 'assert';
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.

7.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.

7.2.1. Documenting results in code examples via assertions

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

function id(x) {
  return x;
}

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

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.

7.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:

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

For more information, consult the chapter on quizzes and exercises

7.3. Normal comparison versus deep comparison

The strict .equal() uses === to compare values. That means that an object is only equal to itself – even if two objects have the same content:

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

In such cases, you can use .deepEqual():

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

This method works for Arrays, too:

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

7.4. Quick reference: module assert

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

7.4.1. Normal equality

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

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

    assert.notEqual(3+3, 22);
    

7.4.2. Deep equality

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

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

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

7.4.3. Expecting exceptions

If you want to (or expect to) receive an exception, you need .throws:

  • function throws(block: Function, message?: string): void

    assert.throws(
      () => {
        null.prop;
      }
    );
    
  • function throws(block: Function, error: Function, message?: string): void

    assert.throws(
      () => {
        null.prop;
      },
      TypeError
    );
    
  • function throws(block: Function, error: RegExp, message?: string): void

    assert.throws(
      () => {
        null.prop;
      },
      /^TypeError: Cannot read property 'prop' of null$/
    );
    
  • function throws(block: Function, error: Object, message?: string): void

    assert.throws(
      () => {
        null.prop;
      },
      {
        name: 'TypeError',
        message: Cannot read property 'prop' of null,
      }
    );
    

7.4.4. Other tool functions

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

    try {
      functionThatShouldThrow();
      assert.fail();
    } catch (_) {
      // Success
    }
    

Quiz

See quiz app.

Comments

Next: 8. Getting started with quizzes and exercises