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:
import * as assert from 'assert/strict';
.equal(3 + 5, 8); assert
This assertion states that the expected result of 3 plus 5 is 8. The import statement uses the recommended strict
version of assert
.
In this book, assertions are used in two ways: to document results in code examples and to implement test-driven exercises.
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:
.equal(id('abc'), 'abc'); assert
In the examples, I usually omit the statement for importing assert
.
The motivation behind using assertions is:
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', () => {
.equal(hello('world'), 'Hello world!');
assert.equal(hello('Jane'), 'Hello Jane!');
assert.equal(hello('John'), 'Hello John!');
assert.equal(hello(''), 'Hello !');
assert; })
For more information, consult §10 “Getting started with quizzes and exercises”.
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):
.notEqual({foo: 1}, {foo: 1}); assert
deepEqual()
is a better choice for comparing objects:
.deepEqual({foo: 1}, {foo: 1}); assert
This method works for Arrays, too:
.notEqual(['a', 'b', 'c'], ['a', 'b', 'c']);
assert.deepEqual(['a', 'b', 'c'], ['a', 'b', 'c']); assert
assert
For the full documentation, see the Node.js docs.
function equal(actual: any, expected: any, message?: string): void
actual === expected
must be true
. If not, an AssertionError
is thrown.
.equal(3+3, 6); assert
function notEqual(actual: any, expected: any, message?: string): void
actual !== expected
must be true
. If not, an AssertionError
is thrown.
.notEqual(3+3, 22); assert
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.
let e;
try {
const x = 3;
.equal(x, 8, 'x must be equal to 8')
assertcatch (err) {
} .equal(
assertString(err),
'AssertionError [ERR_ASSERTION]: x must be equal to 8');
}
function deepEqual(actual: any, expected: any, message?: string): void
actual
must be deeply equal to expected
. If not, an AssertionError
is thrown.
.deepEqual([1,2,3], [1,2,3]);
assert.deepEqual([], []);
assert
// To .equal(), an object is only equal to itself:
.notEqual([], []); assert
function notDeepEqual(actual: any, expected: any, message?: string): void
actual
must not be deeply equal to expected
. If it is, an AssertionError
is thrown.
.notDeepEqual([1,2,3], [1,2]); assert
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
.throws(
assert=> {
() null.prop;
}; )
function throws(block: Function, error: Function, message?: string): void
.throws(
assert=> {
() null.prop;
,
}TypeError
; )
function throws(block: Function, error: RegExp, message?: string): void
.throws(
assert=> {
() null.prop;
,
}/^TypeError: Cannot read properties of null \(reading 'prop'\)$/
; )
function throws(block: Function, error: Object, message?: string): void
.throws(
assert=> {
() null.prop;
,
}
{name: 'TypeError',
message: "Cannot read properties of null (reading 'prop')",
}; )
function fail(message: string | Error): never
Always throws an AssertionError
when it is called. That is occasionally useful for unit testing.
try {
functionThatShouldThrow();
.fail();
assertcatch (_) {
} // Success
}
Quiz
See quiz app.