Assert#
Source Code: lib/assert.js
The node:assert module provides a set of assertion functions for verifying
invariants.
Strict assertion mode#
In strict assertion mode, non-strict methods behave like their corresponding
strict methods. For example, assert.deepEqual() will behave like
assert.deepStrictEqual().
In strict assertion mode, error messages for objects display a diff. In legacy
assertion mode, error messages for objects display the objects, often truncated.
To use strict assertion mode:
import { strict as assert } from 'node:assert';const assert = require('node:assert').strict;
import assert from 'node:assert/strict';const assert = require('node:assert/strict');
Example error diff:
import { strict as assert } from 'node:assert';
assert.deepEqual([[[1, 2, 3]], 4, 5], [[[1, 2, '3']], 4, 5]);
const assert = require('node:assert/strict');
assert.deepEqual([[[1, 2, 3]], 4, 5], [[[1, 2, '3']], 4, 5]);
To deactivate the colors, use the NO_COLOR or NODE_DISABLE_COLORS
environment variables. This will also deactivate the colors in the REPL. For
more on color support in terminal environments, read the tty
getColorDepth() documentation.
Legacy assertion mode#
Legacy assertion mode uses the == operator in:
To use legacy assertion mode:
import assert from 'node:assert';const assert = require('node:assert');
Legacy assertion mode may have surprising results, especially when using
assert.deepEqual():
assert.deepEqual(/a/gi, new Date());
Class: assert.AssertionError#
Indicates the failure of an assertion. All errors thrown by the node:assert
module will be instances of the AssertionError class.
new assert.AssertionError(options)#
Added in: v0.1.21
options <Object>
message <string> If provided, the error message is set to this value.
actual <any> The actual property on the error instance.
expected <any> The expected property on the error instance.
operator <string> The operator property on the error instance.
stackStartFn <Function> If provided, the generated stack trace omits
frames before this function.
diff <string> If set to 'full', shows the full diff in assertion errors. Defaults to 'simple'.
Accepted values: 'simple', 'full'.
A subclass of <Error> that indicates the failure of an assertion.
All instances contain the built-in Error properties (message and name)
and:
actual <any> Set to the actual argument for methods such as
assert.strictEqual().
expected <any> Set to the expected value for methods such as
assert.strictEqual().
generatedMessage <boolean> Indicates if the message was auto-generated
(true) or not.
code <string> Value is always ERR_ASSERTION to show that the error is an
assertion error.
operator <string> Set to the passed in operator value.
import assert from 'node:assert';
const { message } = new assert.AssertionError({
actual: 1,
expected: 2,
operator: 'strictEqual',
});
try {
assert.strictEqual(1, 2);
} catch (err) {
assert(err instanceof assert.AssertionError);
assert.strictEqual(err.message, message);
assert.strictEqual(err.name, 'AssertionError');
assert.strictEqual(err.actual, 1);
assert.strictEqual(err.expected, 2);
assert.strictEqual(err.code, 'ERR_ASSERTION');
assert.strictEqual(err.operator, 'strictEqual');
assert.strictEqual(err.generatedMessage, true);
}const assert = require('node:assert');
const { message } = new assert.AssertionError({
actual: 1,
expected: 2,
operator: 'strictEqual',
});
try {
assert.strictEqual(1, 2);
} catch (err) {
assert(err instanceof assert.AssertionError);
assert.strictEqual(err.message, message);
assert.strictEqual(err.name, 'AssertionError');
assert.strictEqual(err.actual, 1);
assert.strictEqual(err.expected, 2);
assert.strictEqual(err.code, 'ERR_ASSERTION');
assert.strictEqual(err.operator, 'strictEqual');
assert.strictEqual(err.generatedMessage, true);
}
Class: assert.Assert#
Added in: v22.19.0
The Assert class allows creating independent assertion instances with custom options.
new assert.Assert([options])#
options <Object>
diff <string> If set to 'full', shows the full diff in assertion errors. Defaults to 'simple'.
Accepted values: 'simple', 'full'.
strict <boolean> If set to true, non-strict methods behave like their
corresponding strict methods. Defaults to true.
Creates a new assertion instance. The diff option controls the verbosity of diffs in assertion error messages.
const { Assert } = require('node:assert');
const assertInstance = new Assert({ diff: 'full' });
assertInstance.deepStrictEqual({ a: 1 }, { a: 2 });
Important: When destructuring assertion methods from an Assert instance,
the methods lose their connection to the instance's configuration options (such as diff and strict settings).
The destructured methods will fall back to default behavior instead.
const myAssert = new Assert({ diff: 'full' });
myAssert.strictEqual({ a: 1 }, { b: { c: 1 } });
const { strictEqual } = myAssert;
strictEqual({ a: 1 }, { b: { c: 1 } });
When destructured, methods lose access to the instance's this context and revert to default assertion behavior
(diff: 'simple', non-strict mode).
To maintain custom options when using destructured methods, avoid
destructuring and call methods directly on the instance.
Class: assert.CallTracker#
This feature is deprecated and will be removed in a future version.
Please consider using alternatives such as the
mock helper function.
tracker.getCalls(fn)#
Added in: v18.8.0, v16.18.0
import assert from 'node:assert';
const tracker = new assert.CallTracker();
function func() {}
const callsfunc = tracker.calls(func);
callsfunc(1, 2, 3);
assert.deepStrictEqual(tracker.getCalls(callsfunc),
[{ thisArg: undefined, arguments: [1, 2, 3] }]);const assert = require('node:assert');
const tracker = new assert.CallTracker();
function func() {}
const callsfunc = tracker.calls(func);
callsfunc(1, 2, 3);
assert.deepStrictEqual(tracker.getCalls(callsfunc),
[{ thisArg: undefined, arguments: [1, 2, 3] }]);
assert(value[, message])#
Added in: v0.5.9
An alias of assert.ok().
assert.deepEqual(actual, expected[, message])#
Strict assertion mode
An alias of assert.deepStrictEqual().
Legacy assertion mode
Tests for deep equality between the actual and expected parameters. Consider
using assert.deepStrictEqual() instead. assert.deepEqual() can have
surprising results.
Deep equality means that the enumerable "own" properties of child objects
are also recursively evaluated by the following rules.
Comparison details#
- Primitive values are compared with the
== operator,
with the exception of <NaN>. It is treated as being identical in case
both sides are <NaN>.
- Type tags of objects should be the same.
- Only enumerable "own" properties are considered.
- <Error> names, messages, causes, and errors are always compared,
even if these are not enumerable properties.
- Object wrappers are compared both as objects and unwrapped values.
Object properties are compared unordered.
- <Map> keys and <Set> items are compared unordered.
- Recursion stops when both sides differ or both sides encounter a circular
reference.
- Implementation does not test the
[[Prototype]] of
objects.
- <Symbol> properties are not compared.
- <WeakMap> and <WeakSet> comparison does not rely on their values.
- <RegExp> lastIndex, flags, and source are always compared, even if these
are not enumerable properties.
The following example does not throw an AssertionError because the
primitives are compared using the == operator.
import assert from 'node:assert';
assert.deepEqual('+00000000', false);const assert = require('node:assert');
assert.deepEqual('+00000000', false);
"Deep" equality means that the enumerable "own" properties of child objects
are evaluated also:
import assert from 'node:assert';
const obj1 = {
a: {
b: 1,
},
};
const obj2 = {
a: {
b: 2,
},
};
const obj3 = {
a: {
b: 1,
},
};
const obj4 = { __proto__: obj1 };
assert.deepEqual(obj1, obj1);
assert.deepEqual(obj1, obj2);
assert.deepEqual(obj1, obj3);
assert.deepEqual(obj1, obj4);
const assert = require('node:assert');
const obj1 = {
a: {
b: 1,
},
};
const obj2 = {
a: {
b: 2,
},
};
const obj3 = {
a: {
b: 1,
},
};
const obj4 = { __proto__: obj1 };
assert.deepEqual(obj1, obj1);
assert.deepEqual(obj1, obj2);
assert.deepEqual(obj1, obj3);
assert.deepEqual(obj1, obj4);
If the values are not equal, an AssertionError is thrown with a message
property set equal to the value of the message parameter. If the message
parameter is undefined, a default error message is assigned. If the message
parameter is an instance of <Error> then it will be thrown instead of the
AssertionError.
assert.deepStrictEqual(actual, expected[, message])#
Tests for deep equality between the actual and expected parameters.
"Deep" equality means that the enumerable "own" properties of child objects
are recursively evaluated also by the following rules.
Comparison details#
- Primitive values are compared using
Object.is().
- Type tags of objects should be the same.
[[Prototype]] of objects are compared using
the === operator.
- Only enumerable "own" properties are considered.
- <Error> names, messages, causes, and errors are always compared,
even if these are not enumerable properties.
errors is also compared.
- Enumerable own <Symbol> properties are compared as well.
- Object wrappers are compared both as objects and unwrapped values.
Object properties are compared unordered.
- <Map> keys and <Set> items are compared unordered.
- Recursion stops when both sides differ or both sides encounter a circular
reference.
- <WeakMap> and <WeakSet> instances are not compared structurally.
They are only equal if they reference the same object. Any comparison between
different
WeakMap or WeakSet instances will result in inequality,
even if they contain the same entries.
- <RegExp> lastIndex, flags, and source are always compared, even if these
are not enumerable properties.
import assert from 'node:assert/strict';
assert.deepStrictEqual({ a: 1 }, { a: '1' });
const date = new Date();
const object = {};
const fakeDate = {};
Object.setPrototypeOf(fakeDate, Date.prototype);
assert.deepStrictEqual(object, fakeDate);
assert.deepStrictEqual(date, fakeDate);
assert.deepStrictEqual(NaN, NaN);
assert.deepStrictEqual(new Number(1), new Number(2));
assert.deepStrictEqual(new String('foo'), Object('foo'));
assert.deepStrictEqual(-0, -0);
assert.deepStrictEqual(0, -0);
const symbol1 = Symbol();
const symbol2 = Symbol();
assert.deepStrictEqual({ [symbol1]: 1 }, { [symbol1]: 1 });
assert.deepStrictEqual({ [symbol1]: 1 }, { [symbol2]: 1 });
const weakMap1 = new WeakMap();
const weakMap2 = new WeakMap();
const obj = {};
weakMap1.set(obj, 'value');
weakMap2.set(obj, 'value');
assert.deepStrictEqual(weakMap1, weakMap2);
assert.deepStrictEqual(weakMap1, weakMap1);
const weakSet1 = new WeakSet();
const weakSet2 = new WeakSet();
weakSet1.add(obj);
weakSet2.add(obj);
assert.deepStrictEqual(weakSet1, weakSet2);
assert.deepStrictEqual(weakSet1, weakSet1);
const assert = require('node:assert/strict');
assert.deepStrictEqual({ a: 1 }, { a: '1' });
const date = new Date();
const object = {};
const fakeDate = {};
Object.setPrototypeOf(fakeDate, Date.prototype);
assert.deepStrictEqual(object, fakeDate);
assert.deepStrictEqual(date, fakeDate);
assert.deepStrictEqual(NaN, NaN);
assert.deepStrictEqual(new Number(1), new Number(2));
assert.deepStrictEqual(new String('foo'), Object('foo'));
assert.deepStrictEqual(-0, -0);
assert.deepStrictEqual(0, -0);
const symbol1 = Symbol();
const symbol2 = Symbol();
assert.deepStrictEqual({ [symbol1]: 1 }, { [symbol1]: 1 });
assert.deepStrictEqual({ [symbol1]: 1 }, { [symbol2]: 1 });
const weakMap1 = new WeakMap();
const weakMap2 = new WeakMap();
const obj = {};
weakMap1.set(obj, 'value');
weakMap2.set(obj, 'value');
assert.deepStrictEqual(weakMap1, weakMap2);
assert.deepStrictEqual(weakMap1, weakMap1);
const weakSet1 = new WeakSet();
const weakSet2 = new WeakSet();
weakSet1.add(obj);
weakSet2.add(obj);
assert.deepStrictEqual(weakSet1, weakSet2);
assert.deepStrictEqual(weakSet1, weakSet1);
If the values are not equal, an AssertionError is thrown with a message
property set equal to the value of the message parameter. If the message
parameter is undefined, a default error message is assigned. If the message
parameter is an instance of <Error> then it will be thrown instead of the
AssertionError.
assert.doesNotMatch(string, regexp[, message])#
Expects the string input not to match the regular expression.
import assert from 'node:assert/strict';
assert.doesNotMatch('I will fail', /fail/);
assert.doesNotMatch(123, /pass/);
assert.doesNotMatch('I will pass', /different/);
const assert = require('node:assert/strict');
assert.doesNotMatch('I will fail', /fail/);
assert.doesNotMatch(123, /pass/);
assert.doesNotMatch('I will pass', /different/);
If the values do match, or if the string argument is of another type than
string, an AssertionError is thrown with a message property set equal
to the value of the message parameter. If the message parameter is
undefined, a default error message is assigned. If the message parameter is an
instance of <Error> then it will be thrown instead of the
AssertionError.
assert.doesNotReject(asyncFn[, error][, message])#
Added in: v10.0.0
Awaits the asyncFn promise or, if asyncFn is a function, immediately
calls the function and awaits the returned promise to complete. It will then
check that the promise is not rejected.
If asyncFn is a function and it throws an error synchronously,
assert.doesNotReject() will return a rejected Promise with that error. If
the function does not return a promise, assert.doesNotReject() will return a
rejected Promise with an ERR_INVALID_RETURN_VALUE error. In both cases
the error handler is skipped.
Using assert.doesNotReject() is actually not useful because there is little
benefit in catching a rejection and then rejecting it again. Instead, consider
adding a comment next to the specific code path that should not reject and keep
error messages as expressive as possible.
If specified, error can be a Class, <RegExp> or a validation
function. See assert.throws() for more details.
Besides the async nature to await the completion behaves identically to
assert.doesNotThrow().
import assert from 'node:assert/strict';
await assert.doesNotReject(
async () => {
throw new TypeError('Wrong value');
},
SyntaxError,
);const assert = require('node:assert/strict');
(async () => {
await assert.doesNotReject(
async () => {
throw new TypeError('Wrong value');
},
SyntaxError,
);
})();
import assert from 'node:assert/strict';
assert.doesNotReject(Promise.reject(new TypeError('Wrong value')))
.then(() => {
});const assert = require('node:assert/strict');
assert.doesNotReject(Promise.reject(new TypeError('Wrong value')))
.then(() => {
});
assert.doesNotThrow(fn[, error][, message])#
Asserts that the function fn does not throw an error.
Using assert.doesNotThrow() is actually not useful because there
is no benefit in catching an error and then rethrowing it. Instead, consider
adding a comment next to the specific code path that should not throw and keep
error messages as expressive as possible.
When assert.doesNotThrow() is called, it will immediately call the fn
function.
If an error is thrown and it is the same type as that specified by the error
parameter, then an AssertionError is thrown. If the error is of a
different type, or if the error parameter is undefined, the error is
propagated back to the caller.
If specified, error can be a Class, <RegExp>, or a validation
function. See assert.throws() for more details.
The following, for instance, will throw the <TypeError> because there is no
matching error type in the assertion:
import assert from 'node:assert/strict';
assert.doesNotThrow(
() => {
throw new TypeError('Wrong value');
},
SyntaxError,
);const assert = require('node:assert/strict');
assert.doesNotThrow(
() => {
throw new TypeError('Wrong value');
},
SyntaxError,
);
However, the following will result in an AssertionError with the message
'Got unwanted exception...':
import assert from 'node:assert/strict';
assert.doesNotThrow(
() => {
throw new TypeError('Wrong value');
},
TypeError,
);const assert = require('node:assert/strict');
assert.doesNotThrow(
() => {
throw new TypeError('Wrong value');
},
TypeError,
);
If an AssertionError is thrown and a value is provided for the message
parameter, the value of message will be appended to the AssertionError
message:
import assert from 'node:assert/strict';
assert.doesNotThrow(
() => {
throw new TypeError('Wrong value');
},
/Wrong value/,
'Whoops',
);
const assert = require('node:assert/strict');
assert.doesNotThrow(
() => {
throw new TypeError('Wrong value');
},
/Wrong value/,
'Whoops',
);
assert.equal(actual, expected[, message])#
Strict assertion mode
An alias of assert.strictEqual().
Legacy assertion mode
Tests shallow, coercive equality between the actual and expected parameters
using the == operator. NaN is specially handled
and treated as being identical if both sides are NaN.
import assert from 'node:assert';
assert.equal(1, 1);
assert.equal(1, '1');
assert.equal(NaN, NaN);
assert.equal(1, 2);
assert.equal({ a: { b: 1 } }, { a: { b: 1 } });
const assert = require('node:assert');
assert.equal(1, 1);
assert.equal(1, '1');
assert.equal(NaN, NaN);
assert.equal(1, 2);
assert.equal({ a: { b: 1 } }, { a: { b: 1 } });
If the values are not equal, an AssertionError is thrown with a message
property set equal to the value of the message parameter. If the message
parameter is undefined, a default error message is assigned. If the message
parameter is an instance of <Error> then it will be thrown instead of the
AssertionError.
assert.fail([message])#
Added in: v0.1.21
Throws an AssertionError with the provided error message or a default
error message. If the message parameter is an instance of <Error> then
it will be thrown instead of the AssertionError.
import assert from 'node:assert/strict';
assert.fail();
assert.fail('boom');
assert.fail(new TypeError('need array'));
const assert = require('node:assert/strict');
assert.fail();
assert.fail('boom');
assert.fail(new TypeError('need array'));
Using assert.fail() with more than two arguments is possible but deprecated.
See below for further details.
assert.fail(actual, expected[, message[, operator[, stackStartFn]]])#
Stability: 0 - Deprecated: Use
assert.fail([message]) or other assert
functions instead.
If message is falsy, the error message is set as the values of actual and
expected separated by the provided operator. If just the two actual and
expected arguments are provided, operator will default to '!='. If
message is provided as third argument it will be used as the error message and
the other arguments will be stored as properties on the thrown object. If
stackStartFn is provided, all stack frames above that function will be
removed from stacktrace (see Error.captureStackTrace). If no arguments are
given, the default message Failed will be used.
import assert from 'node:assert/strict';
assert.fail('a', 'b');
assert.fail(1, 2, undefined, '>');
assert.fail(1, 2, 'fail');
assert.fail(1, 2, 'whoops', '>');
assert.fail(1, 2, new TypeError('need array'));
const assert = require('node:assert/strict');
assert.fail('a', 'b');
assert.fail(1, 2, undefined, '>');
assert.fail(1, 2, 'fail');
assert.fail(1, 2, 'whoops', '>');
assert.fail(1, 2, new TypeError('need array'));
In the last three cases actual, expected, and operator have no
influence on the error message.
Example use of stackStartFn for truncating the exception's stacktrace:
import assert from 'node:assert/strict';
function suppressFrame() {
assert.fail('a', 'b', undefined, '!==', suppressFrame);
}
suppressFrame();
const assert = require('node:assert/strict');
function suppressFrame() {
assert.fail('a', 'b', undefined, '!==', suppressFrame);
}
suppressFrame();
assert.match(string, regexp[, message])#
Expects the string input to match the regular expression.
import assert from 'node:assert/strict';
assert.match('I will fail', /pass/);
assert.match(123, /pass/);
assert.match('I will pass', /pass/);
const assert = require('node:assert/strict');
assert.match('I will fail', /pass/);
assert.match(123, /pass/);
assert.match('I will pass', /pass/);
If the values do not match, or if the string argument is of another type than
string, an AssertionError is thrown with a message property set equal
to the value of the message parameter. If the message parameter is
undefined, a default error message is assigned. If the message parameter is an
instance of <Error> then it will be thrown instead of the
AssertionError.
assert.notDeepEqual(actual, expected[, message])#
Strict assertion mode
An alias of assert.notDeepStrictEqual().
Legacy assertion mode
Tests for any deep inequality. Opposite of assert.deepEqual().
import assert from 'node:assert';
const obj1 = {
a: {
b: 1,
},
};
const obj2 = {
a: {
b: 2,
},
};
const obj3 = {
a: {
b: 1,
},
};
const obj4 = { __proto__: obj1 };
assert.notDeepEqual(obj1, obj1);
assert.notDeepEqual(obj1, obj2);
assert.notDeepEqual(obj1, obj3);
assert.notDeepEqual(obj1, obj4);
const assert = require('node:assert');
const obj1 = {
a: {
b: 1,
},
};
const obj2 = {
a: {
b: 2,
},
};
const obj3 = {
a: {
b: 1,
},
};
const obj4 = { __proto__: obj1 };
assert.notDeepEqual(obj1, obj1);
assert.notDeepEqual(obj1, obj2);
assert.notDeepEqual(obj1, obj3);
assert.notDeepEqual(obj1, obj4);
If the values are deeply equal, an AssertionError is thrown with a
message property set equal to the value of the message parameter. If the
message parameter is undefined, a default error message is assigned. If the
message parameter is an instance of <Error> then it will be thrown
instead of the AssertionError.
assert.notEqual(actual, expected[, message])#
Strict assertion mode
An alias of assert.notStrictEqual().
Legacy assertion mode
Tests shallow, coercive inequality with the != operator. NaN is
specially handled and treated as being identical if both sides are NaN.
import assert from 'node:assert';
assert.notEqual(1, 2);
assert.notEqual(1, 1);
assert.notEqual(1, '1');
const assert = require('node:assert');
assert.notEqual(1, 2);
assert.notEqual(1, 1);
assert.notEqual(1, '1');
If the values are equal, an AssertionError is thrown with a message
property set equal to the value of the message parameter. If the message
parameter is undefined, a default error message is assigned. If the message
parameter is an instance of <Error> then it will be thrown instead of the
AssertionError.
assert.notStrictEqual(actual, expected[, message])#
Tests strict inequality between the actual and expected parameters as
determined by Object.is().
import assert from 'node:assert/strict';
assert.notStrictEqual(1, 2);
assert.notStrictEqual(1, 1);
assert.notStrictEqual(1, '1');
const assert = require('node:assert/strict');
assert.notStrictEqual(1, 2);
assert.notStrictEqual(1, 1);
assert.notStrictEqual(1, '1');
If the values are strictly equal, an AssertionError is thrown with a
message property set equal to the value of the message parameter. If the
message parameter is undefined, a default error message is assigned. If the
message parameter is an instance of <Error> then it will be thrown
instead of the AssertionError.
assert.rejects(asyncFn[, error][, message])#
Added in: v10.0.0
Awaits the asyncFn promise or, if asyncFn is a function, immediately
calls the function and awaits the returned promise to complete. It will then
check that the promise is rejected.
If asyncFn is a function and it throws an error synchronously,
assert.rejects() will return a rejected Promise with that error. If the
function does not return a promise, assert.rejects() will return a rejected
Promise with an ERR_INVALID_RETURN_VALUE error. In both cases the error
handler is skipped.
Besides the async nature to await the completion behaves identically to
assert.throws().
If specified, error can be a Class, <RegExp>, a validation function,
an object where each property will be tested for, or an instance of error where
each property will be tested for including the non-enumerable message and
name properties.
If specified, message will be the message provided by the AssertionError
if the asyncFn fails to reject.
import assert from 'node:assert/strict';
await assert.rejects(
async () => {
throw new TypeError('Wrong value');
},
{
name: 'TypeError',
message: 'Wrong value',
},
);const assert = require('node:assert/strict');
(async () => {
await assert.rejects(
async () => {
throw new TypeError('Wrong value');
},
{
name: 'TypeError',
message: 'Wrong value',
},
);
})();
import assert from 'node:assert/strict';
await assert.rejects(
async () => {
throw new TypeError('Wrong value');
},
(err) => {
assert.strictEqual(err.name, 'TypeError');
assert.strictEqual(err.message, 'Wrong value');
return true;
},
);const assert = require('node:assert/strict');
(async () => {
await assert.rejects(
async () => {
throw new TypeError('Wrong value');
},
(err) => {
assert.strictEqual(err.name, 'TypeError');
assert.strictEqual(err.message, 'Wrong value');
return true;
},
);
})();
import assert from 'node:assert/strict';
assert.rejects(
Promise.reject(new Error('Wrong value')),
Error,
).then(() => {
});const assert = require('node:assert/strict');
assert.rejects(
Promise.reject(new Error('Wrong value')),
Error,
).then(() => {
});
error cannot be a string. If a string is provided as the second
argument, then error is assumed to be omitted and the string will be used for
message instead. This can lead to easy-to-miss mistakes. Please read the
example in assert.throws() carefully if using a string as the second
argument gets considered.
assert.strictEqual(actual, expected[, message])#
Tests strict equality between the actual and expected parameters as
determined by Object.is().
import assert from 'node:assert/strict';
assert.strictEqual(1, 2);
assert.strictEqual(1, 1);
assert.strictEqual('Hello foobar', 'Hello World!');
const apples = 1;
const oranges = 2;
assert.strictEqual(apples, oranges, `apples ${apples} !== oranges ${oranges}`);
assert.strictEqual(1, '1', new TypeError('Inputs are not identical'));
const assert = require('node:assert/strict');
assert.strictEqual(1, 2);
assert.strictEqual(1, 1);
assert.strictEqual('Hello foobar', 'Hello World!');
const apples = 1;
const oranges = 2;
assert.strictEqual(apples, oranges, `apples ${apples} !== oranges ${oranges}`);
assert.strictEqual(1, '1', new TypeError('Inputs are not identical'));
If the values are not strictly equal, an AssertionError is thrown with a
message property set equal to the value of the message parameter. If the
message parameter is undefined, a default error message is assigned. If the
message parameter is an instance of <Error> then it will be thrown
instead of the AssertionError.
assert.throws(fn[, error][, message])#
Expects the function fn to throw an error.
If specified, error can be a Class, <RegExp>, a validation function,
a validation object where each property will be tested for strict deep equality,
or an instance of error where each property will be tested for strict deep
equality including the non-enumerable message and name properties. When
using an object, it is also possible to use a regular expression, when
validating against a string property. See below for examples.
If specified, message will be appended to the message provided by the
AssertionError if the fn call fails to throw or in case the error validation
fails.
Custom validation object/error instance:
import assert from 'node:assert/strict';
const err = new TypeError('Wrong value');
err.code = 404;
err.foo = 'bar';
err.info = {
nested: true,
baz: 'text',
};
err.reg = /abc/i;
assert.throws(
() => {
throw err;
},
{
name: 'TypeError',
message: 'Wrong value',
info: {
nested: true,
baz: 'text',
},
},
);
assert.throws(
() => {
throw err;
},
{
name: /^TypeError$/,
message: /Wrong/,
foo: 'bar',
info: {
nested: true,
baz: 'text',
},
reg: /abc/i,
},
);
assert.throws(
() => {
const otherErr = new Error('Not found');
for (const [key, value] of Object.entries(err)) {
otherErr[key] = value;
}
throw otherErr;
},
err,
);const assert = require('node:assert/strict');
const err = new TypeError('Wrong value');
err.code = 404;
err.foo = 'bar';
err.info = {
nested: true,
baz: 'text',
};
err.reg = /abc/i;
assert.throws(
() => {
throw err;
},
{
name: 'TypeError',
message: 'Wrong value',
info: {
nested: true,
baz: 'text',
},
},
);
assert.throws(
() => {
throw err;
},
{
name: /^TypeError$/,
message: /Wrong/,
foo: 'bar',
info: {
nested: true,
baz: 'text',
},
reg: /abc/i,
},
);
assert.throws(
() => {
const otherErr = new Error('Not found');
for (const [key, value] of Object.entries(err)) {
otherErr[key] = value;
}
throw otherErr;
},
err,
);
Validate instanceof using constructor:
import assert from 'node:assert/strict';
assert.throws(
() => {
throw new Error('Wrong value');
},
Error,
);const assert = require('node:assert/strict');
assert.throws(
() => {
throw new Error('Wrong value');
},
Error,
);
Validate error message using <RegExp>:
Using a regular expression runs .toString on the error object, and will
therefore also include the error name.
import assert from 'node:assert/strict';
assert.throws(
() => {
throw new Error('Wrong value');
},
/^Error: Wrong value$/,
);const assert = require('node:assert/strict');
assert.throws(
() => {
throw new Error('Wrong value');
},
/^Error: Wrong value$/,
);
Custom error validation:
The function must return true to indicate all internal validations passed.
It will otherwise fail with an AssertionError.
import assert from 'node:assert/strict';
assert.throws(
() => {
throw new Error('Wrong value');
},
(err) => {
assert(err instanceof Error);
assert(/value/.test(err));
return true;
},
'unexpected error',
);const assert = require('node:assert/strict');
assert.throws(
() => {
throw new Error('Wrong value');
},
(err) => {
assert(err instanceof Error);
assert(/value/.test(err));
return true;
},
'unexpected error',
);
error cannot be a string. If a string is provided as the second
argument, then error is assumed to be omitted and the string will be used for
message instead. This can lead to easy-to-miss mistakes. Using the same
message as the thrown error message is going to result in an
ERR_AMBIGUOUS_ARGUMENT error. Please read the example below carefully if using
a string as the second argument gets considered:
import assert from 'node:assert/strict';
function throwingFirst() {
throw new Error('First');
}
function throwingSecond() {
throw new Error('Second');
}
function notThrowing() {}
assert.throws(throwingFirst, 'Second');
assert.throws(throwingSecond, 'Second');
assert.throws(notThrowing, 'Second');
assert.throws(throwingSecond, /Second$/);
assert.throws(throwingFirst, /Second$/);
const assert = require('node:assert/strict');
function throwingFirst() {
throw new Error('First');
}
function throwingSecond() {
throw new Error('Second');
}
function notThrowing() {}
assert.throws(throwingFirst, 'Second');
assert.throws(throwingSecond, 'Second');
assert.throws(notThrowing, 'Second');
assert.throws(throwingSecond, /Second$/);
assert.throws(throwingFirst, /Second$/);
Due to the confusing error-prone notation, avoid a string as the second
argument.
assert.partialDeepStrictEqual(actual, expected[, message])#
Tests for partial deep equality between the actual and expected parameters.
"Deep" equality means that the enumerable "own" properties of child objects
are recursively evaluated also by the following rules. "Partial" equality means
that only properties that exist on the expected parameter are going to be
compared.
This method always passes the same test cases as assert.deepStrictEqual(),
behaving as a super set of it.
Comparison details#
- Primitive values are compared using
Object.is().
- Type tags of objects should be the same.
[[Prototype]] of objects are not compared.
- Only enumerable "own" properties are considered.
- <Error> names, messages, causes, and errors are always compared,
even if these are not enumerable properties.
errors is also compared.
- Enumerable own <Symbol> properties are compared as well.
- Object wrappers are compared both as objects and unwrapped values.
Object properties are compared unordered.
- <Map> keys and <Set> items are compared unordered.
- Recursion stops when both sides differ or both sides encounter a circular
reference.
- <WeakMap> and <WeakSet> instances are not compared structurally.
They are only equal if they reference the same object. Any comparison between
different
WeakMap or WeakSet instances will result in inequality,
even if they contain the same entries.
- <RegExp> lastIndex, flags, and source are always compared, even if these
are not enumerable properties.
- Holes in sparse arrays are ignored.
import assert from 'node:assert';
assert.partialDeepStrictEqual(
{ a: { b: { c: 1 } } },
{ a: { b: { c: 1 } } },
);
assert.partialDeepStrictEqual(
{ a: 1, b: 2, c: 3 },
{ b: 2 },
);
assert.partialDeepStrictEqual(
[1, 2, 3, 4, 5, 6, 7, 8, 9],
[4, 5, 8],
);
assert.partialDeepStrictEqual(
new Set([{ a: 1 }, { b: 1 }]),
new Set([{ a: 1 }]),
);
assert.partialDeepStrictEqual(
new Map([['key1', 'value1'], ['key2', 'value2']]),
new Map([['key2', 'value2']]),
);
assert.partialDeepStrictEqual(123n, 123n);
assert.partialDeepStrictEqual(
[1, 2, 3, 4, 5, 6, 7, 8, 9],
[5, 4, 8],
);
assert.partialDeepStrictEqual(
{ a: 1 },
{ a: 1, b: 2 },
);
assert.partialDeepStrictEqual(
{ a: { b: 2 } },
{ a: { b: '2' } },
);
const assert = require('node:assert');
assert.partialDeepStrictEqual(
{ a: { b: { c: 1 } } },
{ a: { b: { c: 1 } } },
);
assert.partialDeepStrictEqual(
{ a: 1, b: 2, c: 3 },
{ b: 2 },
);
assert.partialDeepStrictEqual(
[1, 2, 3, 4, 5, 6, 7, 8, 9],
[4, 5, 8],
);
assert.partialDeepStrictEqual(
new Set([{ a: 1 }, { b: 1 }]),
new Set([{ a: 1 }]),
);
assert.partialDeepStrictEqual(
new Map([['key1', 'value1'], ['key2', 'value2']]),
new Map([['key2', 'value2']]),
);
assert.partialDeepStrictEqual(123n, 123n);
assert.partialDeepStrictEqual(
[1, 2, 3, 4, 5, 6, 7, 8, 9],
[5, 4, 8],
);
assert.partialDeepStrictEqual(
{ a: 1 },
{ a: 1, b: 2 },
);
assert.partialDeepStrictEqual(
{ a: { b: 2 } },
{ a: { b: '2' } },
);