{ "type": "module", "source": "doc/api/assert.md", "modules": [ { "textRaw": "Assert", "name": "assert", "introduced_in": "v0.1.21", "stability": 2, "stabilityText": "Stable", "desc": "
The assert
module provides a simple set of assertion tests that can be used to\ntest invariants.
A strict
and a legacy
mode exist, while it is recommended to only use\nstrict mode
.
For more information about the used equality comparisons see\nMDN's guide on equality comparisons and sameness.
", "classes": [ { "textRaw": "Class: assert.AssertionError", "type": "class", "name": "assert.AssertionError", "desc": "A subclass of Error
that indicates the failure of an assertion. All errors\nthrown by the assert
module will be instances of the AssertionError
class.
A subclass of Error
that indicates the failure of an assertion.
All instances contain the built-in Error
properties (message
and name
)\nand:
actual
<any> Set to the actual value in case e.g.,\nassert.strictEqual()
is used.expected
<any> Set to the expected value in case e.g.,\nassert.strictEqual()
is used.generatedMessage
<boolean> Indicates if the message was auto-generated\n(true
) or not.code
<string> This is always set to the string ERR_ASSERTION
to indicate\nthat the error is actually an assertion error.operator
<string> Set to the passed in operator value.const assert = require('assert');\n\n// Generate an AssertionError to compare the error message later:\nconst { message } = new assert.AssertionError({\n actual: 1,\n expected: 2,\n operator: 'strictEqual'\n});\n\n// Verify error output:\ntry {\n assert.strictEqual(1, 2);\n} catch (err) {\n assert(err instanceof assert.AssertionError);\n assert.strictEqual(err.message, message);\n assert.strictEqual(err.name, 'AssertionError [ERR_ASSERTION]');\n assert.strictEqual(err.actual, 1);\n assert.strictEqual(err.expected, 2);\n assert.strictEqual(err.code, 'ERR_ASSERTION');\n assert.strictEqual(err.operator, 'strictEqual');\n assert.strictEqual(err.generatedMessage, true);\n}\n
"
}
]
}
],
"modules": [
{
"textRaw": "Strict mode",
"name": "strict_mode",
"meta": {
"added": [
"v9.9.0"
],
"changes": [
{
"version": "v9.9.0",
"pr-url": "https://github.com/nodejs/node/pull/17615",
"description": "Added error diffs to the strict mode"
},
{
"version": "v9.9.0",
"pr-url": "https://github.com/nodejs/node/pull/17002",
"description": "Added strict mode to the assert module."
}
]
},
"desc": "When using the strict mode
, any assert
function will use the equality used\nin the strict function mode. So assert.deepEqual()
will, for example,\nwork the same as assert.deepStrictEqual()
.
On top of that, error messages which involve objects produce an error diff\ninstead of displaying both objects. That is not the case for the legacy mode.
\nIt can be accessed using:
\nconst assert = require('assert').strict;\n
\nExample error diff:
\nconst assert = require('assert').strict;\n\nassert.deepEqual([[[1, 2, 3]], 4, 5], [[[1, 2, '3']], 4, 5]);\n// AssertionError: Expected inputs to be strictly deep-equal:\n// + actual - expected ... Lines skipped\n//\n// [\n// [\n// ...\n// 2,\n// + 3\n// - '3'\n// ],\n// ...\n// 5\n// ]\n
\nTo deactivate the colors, use the NODE_DISABLE_COLORS
environment variable.\nPlease note that this will also deactivate the colors in the REPL.
When accessing assert
directly instead of using the strict
property, the\nAbstract Equality Comparison will be used for any function without \"strict\"\nin its name, such as assert.deepEqual()
.
It can be accessed using:
\nconst assert = require('assert');\n
\nIt is recommended to use the strict mode
instead as the\nAbstract Equality Comparison can often have surprising results. This is\nespecially true for assert.deepEqual()
, where the comparison rules are\nlax:
// WARNING: This does not throw an AssertionError!\nassert.deepEqual(/a/gi, new Date());\n
",
"type": "module",
"displayName": "Legacy mode"
}
],
"methods": [
{
"textRaw": "assert(value[, message])",
"type": "method",
"name": "assert",
"meta": {
"added": [
"v0.5.9"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`value` {any} The input that is checked for being truthy.",
"name": "value",
"type": "any",
"desc": "The input that is checked for being truthy."
},
{
"textRaw": "`message` {string|Error}",
"name": "message",
"type": "string|Error",
"optional": true
}
]
}
],
"desc": "An alias of assert.ok()
.
Strict mode
\nAn alias of assert.deepStrictEqual()
.
Legacy mode
\n\n\nStability: 0 - Deprecated: Use
\nassert.deepStrictEqual()
instead.
Tests for deep equality between the actual
and expected
parameters.\nPrimitive values are compared with the Abstract Equality Comparison\n( ==
).
Only enumerable \"own\" properties are considered. The\nassert.deepEqual()
implementation does not test the\n[[Prototype]]
of objects or enumerable own Symbol
\nproperties. For such checks, consider using assert.deepStrictEqual()
\ninstead. assert.deepEqual()
can have potentially surprising results. The\nfollowing example does not throw an AssertionError
because the properties on\nthe RegExp
object are not enumerable:
// WARNING: This does not throw an AssertionError!\nassert.deepEqual(/a/gi, new Date());\n
\nAn exception is made for Map
and Set
. Map
s and Set
s have their\ncontained items compared too, as expected.
\"Deep\" equality means that the enumerable \"own\" properties of child objects\nare evaluated also:
\nconst assert = require('assert');\n\nconst obj1 = {\n a: {\n b: 1\n }\n};\nconst obj2 = {\n a: {\n b: 2\n }\n};\nconst obj3 = {\n a: {\n b: 1\n }\n};\nconst obj4 = Object.create(obj1);\n\nassert.deepEqual(obj1, obj1);\n// OK\n\n// Values of b are different:\nassert.deepEqual(obj1, obj2);\n// AssertionError: { a: { b: 1 } } deepEqual { a: { b: 2 } }\n\nassert.deepEqual(obj1, obj3);\n// OK\n\n// Prototypes are ignored:\nassert.deepEqual(obj1, obj4);\n// AssertionError: { a: { b: 1 } } deepEqual {}\n
\nIf the values are not equal, an AssertionError
is thrown with a message
\nproperty set equal to the value of the message
parameter. If the message
\nparameter is undefined, a default error message is assigned. If the message
\nparameter is an instance of an Error
then it will be thrown instead of the\nAssertionError
.
Tests for deep equality between the actual
and expected
parameters.\n\"Deep\" equality means that the enumerable \"own\" properties of child objects\nare recursively evaluated also by the following rules.
Object.is()
.[[Prototype]]
of objects are compared using\nthe Strict Equality Comparison.Error
names and messages are always compared, even if these are not\nenumerable properties.Symbol
properties are compared as well.Object
properties are compared unordered.Map
keys and Set
items are compared unordered.WeakMap
and WeakSet
comparison does not rely on their values. See\nbelow for further details.const assert = require('assert').strict;\n\n// This fails because 1 !== '1'.\nassert.deepStrictEqual({ a: 1 }, { a: '1' });\n// AssertionError: Expected inputs to be strictly deep-equal:\n// + actual - expected\n//\n// {\n// + a: 1\n// - a: '1'\n// }\n\n// The following objects don't have own properties\nconst date = new Date();\nconst object = {};\nconst fakeDate = {};\nObject.setPrototypeOf(fakeDate, Date.prototype);\n\n// Different [[Prototype]]:\nassert.deepStrictEqual(object, fakeDate);\n// AssertionError: Expected inputs to be strictly deep-equal:\n// + actual - expected\n//\n// + {}\n// - Date {}\n\n// Different type tags:\nassert.deepStrictEqual(date, fakeDate);\n// AssertionError: Expected inputs to be strictly deep-equal:\n// + actual - expected\n//\n// + 2018-04-26T00:49:08.604Z\n// - Date {}\n\nassert.deepStrictEqual(NaN, NaN);\n// OK, because of the SameValue comparison\n\n// Different unwrapped numbers:\nassert.deepStrictEqual(new Number(1), new Number(2));\n// AssertionError: Expected inputs to be strictly deep-equal:\n// + actual - expected\n//\n// + [Number: 1]\n// - [Number: 2]\n\nassert.deepStrictEqual(new String('foo'), Object('foo'));\n// OK because the object and the string are identical when unwrapped.\n\nassert.deepStrictEqual(-0, -0);\n// OK\n\n// Different zeros using the SameValue Comparison:\nassert.deepStrictEqual(0, -0);\n// AssertionError: Expected inputs to be strictly deep-equal:\n// + actual - expected\n//\n// + 0\n// - -0\n\nconst symbol1 = Symbol();\nconst symbol2 = Symbol();\nassert.deepStrictEqual({ [symbol1]: 1 }, { [symbol1]: 1 });\n// OK, because it is the same symbol on both objects.\n\nassert.deepStrictEqual({ [symbol1]: 1 }, { [symbol2]: 1 });\n// AssertionError [ERR_ASSERTION]: Inputs identical but not reference equal:\n//\n// {\n// [Symbol()]: 1\n// }\n\nconst weakMap1 = new WeakMap();\nconst weakMap2 = new WeakMap([[{}, {}]]);\nconst weakMap3 = new WeakMap();\nweakMap3.unequal = true;\n\nassert.deepStrictEqual(weakMap1, weakMap2);\n// OK, because it is impossible to compare the entries\n\n// Fails because weakMap3 has a property that weakMap1 does not contain:\nassert.deepStrictEqual(weakMap1, weakMap3);\n// AssertionError: Expected inputs to be strictly deep-equal:\n// + actual - expected\n//\n// WeakMap {\n// + [items unknown]\n// - [items unknown],\n// - unequal: true\n// }\n
\nIf the values are not equal, an AssertionError
is thrown with a message
\nproperty set equal to the value of the message
parameter. If the message
\nparameter is undefined, a default error message is assigned. If the message
\nparameter is an instance of an Error
then it will be thrown instead of the\nAssertionError
.
Awaits the asyncFn
promise or, if asyncFn
is a function, immediately\ncalls the function and awaits the returned promise to complete. It will then\ncheck that the promise is not rejected.
If asyncFn
is a function and it throws an error synchronously,\nassert.doesNotReject()
will return a rejected Promise
with that error. If\nthe function does not return a promise, assert.doesNotReject()
will return a\nrejected Promise
with an ERR_INVALID_RETURN_VALUE
error. In both cases\nthe error handler is skipped.
Using assert.doesNotReject()
is actually not useful because there is little\nbenefit in catching a rejection and then rejecting it again. Instead, consider\nadding a comment next to the specific code path that should not reject and keep\nerror messages as expressive as possible.
If specified, error
can be a Class
, RegExp
or a validation\nfunction. See assert.throws()
for more details.
Besides the async nature to await the completion behaves identically to\nassert.doesNotThrow()
.
(async () => {\n await assert.doesNotReject(\n async () => {\n throw new TypeError('Wrong value');\n },\n SyntaxError\n );\n})();\n
\nassert.doesNotReject(Promise.reject(new TypeError('Wrong value')))\n .then(() => {\n // ...\n });\n
"
},
{
"textRaw": "assert.doesNotThrow(fn[, error][, message])",
"type": "method",
"name": "doesNotThrow",
"meta": {
"added": [
"v0.1.21"
],
"changes": [
{
"version": "v5.11.0, v4.4.5",
"pr-url": "https://github.com/nodejs/node/pull/2407",
"description": "The `message` parameter is respected now."
},
{
"version": "v4.2.0",
"pr-url": "https://github.com/nodejs/node/pull/3276",
"description": "The `error` parameter can now be an arrow function."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`fn` {Function}",
"name": "fn",
"type": "Function"
},
{
"textRaw": "`error` {RegExp|Function}",
"name": "error",
"type": "RegExp|Function",
"optional": true
},
{
"textRaw": "`message` {string}",
"name": "message",
"type": "string",
"optional": true
}
]
}
],
"desc": "Asserts that the function fn
does not throw an error.
Using assert.doesNotThrow()
is actually not useful because there\nis no benefit in catching an error and then rethrowing it. Instead, consider\nadding a comment next to the specific code path that should not throw and keep\nerror messages as expressive as possible.
When assert.doesNotThrow()
is called, it will immediately call the fn
\nfunction.
If an error is thrown and it is the same type as that specified by the error
\nparameter, then an AssertionError
is thrown. If the error is of a different\ntype, or if the error
parameter is undefined, the error is propagated back\nto the caller.
If specified, error
can be a Class
, RegExp
or a validation\nfunction. See assert.throws()
for more details.
The following, for instance, will throw the TypeError
because there is no\nmatching error type in the assertion:
assert.doesNotThrow(\n () => {\n throw new TypeError('Wrong value');\n },\n SyntaxError\n);\n
\nHowever, the following will result in an AssertionError
with the message\n'Got unwanted exception...':
assert.doesNotThrow(\n () => {\n throw new TypeError('Wrong value');\n },\n TypeError\n);\n
\nIf an AssertionError
is thrown and a value is provided for the message
\nparameter, the value of message
will be appended to the AssertionError
\nmessage:
assert.doesNotThrow(\n () => {\n throw new TypeError('Wrong value');\n },\n /Wrong value/,\n 'Whoops'\n);\n// Throws: AssertionError: Got unwanted exception: Whoops\n
"
},
{
"textRaw": "assert.equal(actual, expected[, message])",
"type": "method",
"name": "equal",
"meta": {
"added": [
"v0.1.21"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`actual` {any}",
"name": "actual",
"type": "any"
},
{
"textRaw": "`expected` {any}",
"name": "expected",
"type": "any"
},
{
"textRaw": "`message` {string|Error}",
"name": "message",
"type": "string|Error",
"optional": true
}
]
}
],
"desc": "Strict mode
\nAn alias of assert.strictEqual()
.
Legacy mode
\n\n\nStability: 0 - Deprecated: Use
\nassert.strictEqual()
instead.
Tests shallow, coercive equality between the actual
and expected
parameters\nusing the Abstract Equality Comparison ( ==
).
const assert = require('assert');\n\nassert.equal(1, 1);\n// OK, 1 == 1\nassert.equal(1, '1');\n// OK, 1 == '1'\n\nassert.equal(1, 2);\n// AssertionError: 1 == 2\nassert.equal({ a: { b: 1 } }, { a: { b: 1 } });\n// AssertionError: { a: { b: 1 } } == { a: { b: 1 } }\n
\nIf the values are not equal, an AssertionError
is thrown with a message
\nproperty set equal to the value of the message
parameter. If the message
\nparameter is undefined, a default error message is assigned. If the message
\nparameter is an instance of an Error
then it will be thrown instead of the\nAssertionError
.
Throws an AssertionError
with the provided error message or a default error\nmessage. If the message
parameter is an instance of an Error
then it\nwill be thrown instead of the AssertionError
.
const assert = require('assert').strict;\n\nassert.fail();\n// AssertionError [ERR_ASSERTION]: Failed\n\nassert.fail('boom');\n// AssertionError [ERR_ASSERTION]: boom\n\nassert.fail(new TypeError('need array'));\n// TypeError: need array\n
\nUsing assert.fail()
with more than two arguments is possible but deprecated.\nSee below for further details.
If message
is falsy, the error message is set as the values of actual
and\nexpected
separated by the provided operator
. If just the two actual
and\nexpected
arguments are provided, operator
will default to '!='
. If\nmessage
is provided as third argument it will be used as the error message and\nthe other arguments will be stored as properties on the thrown object. If\nstackStartFn
is provided, all stack frames above that function will be\nremoved from stacktrace (see Error.captureStackTrace
). If no arguments are\ngiven, the default message Failed
will be used.
const assert = require('assert').strict;\n\nassert.fail('a', 'b');\n// AssertionError [ERR_ASSERTION]: 'a' != 'b'\n\nassert.fail(1, 2, undefined, '>');\n// AssertionError [ERR_ASSERTION]: 1 > 2\n\nassert.fail(1, 2, 'fail');\n// AssertionError [ERR_ASSERTION]: fail\n\nassert.fail(1, 2, 'whoops', '>');\n// AssertionError [ERR_ASSERTION]: whoops\n\nassert.fail(1, 2, new TypeError('need array'));\n// TypeError: need array\n
\nIn the last three cases actual
, expected
, and operator
have no\ninfluence on the error message.
Example use of stackStartFn
for truncating the exception's stacktrace:
function suppressFrame() {\n assert.fail('a', 'b', undefined, '!==', suppressFrame);\n}\nsuppressFrame();\n// AssertionError [ERR_ASSERTION]: 'a' !== 'b'\n// at repl:1:1\n// at ContextifyScript.Script.runInThisContext (vm.js:44:33)\n// ...\n
"
},
{
"textRaw": "assert.ifError(value)",
"type": "method",
"name": "ifError",
"meta": {
"added": [
"v0.1.97"
],
"changes": [
{
"version": "v10.0.0",
"pr-url": "https://github.com/nodejs/node/pull/18247",
"description": "Instead of throwing the original error it is now wrapped into an `AssertionError` that contains the full stack trace."
},
{
"version": "v10.0.0",
"pr-url": "https://github.com/nodejs/node/pull/18247",
"description": "Value may now only be `undefined` or `null`. Before all falsy values were handled the same as `null` and did not throw."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`value` {any}",
"name": "value",
"type": "any"
}
]
}
],
"desc": "Throws value
if value
is not undefined
or null
. This is useful when\ntesting the error
argument in callbacks. The stack trace contains all frames\nfrom the error passed to ifError()
including the potential new frames for\nifError()
itself.
const assert = require('assert').strict;\n\nassert.ifError(null);\n// OK\nassert.ifError(0);\n// AssertionError [ERR_ASSERTION]: ifError got unwanted exception: 0\nassert.ifError('error');\n// AssertionError [ERR_ASSERTION]: ifError got unwanted exception: 'error'\nassert.ifError(new Error());\n// AssertionError [ERR_ASSERTION]: ifError got unwanted exception: Error\n\n// Create some random error frames.\nlet err;\n(function errorFrame() {\n err = new Error('test error');\n})();\n\n(function ifErrorFrame() {\n assert.ifError(err);\n})();\n// AssertionError [ERR_ASSERTION]: ifError got unwanted exception: test error\n// at ifErrorFrame\n// at errorFrame\n
"
},
{
"textRaw": "assert.notDeepEqual(actual, expected[, message])",
"type": "method",
"name": "notDeepEqual",
"meta": {
"added": [
"v0.1.21"
],
"changes": [
{
"version": "v9.0.0",
"pr-url": "https://github.com/nodejs/node/pull/15001",
"description": "The `Error` names and messages are now properly compared"
},
{
"version": "v8.0.0",
"pr-url": "https://github.com/nodejs/node/pull/12142",
"description": "The `Set` and `Map` content is also compared"
},
{
"version": "v6.4.0, v4.7.1",
"pr-url": "https://github.com/nodejs/node/pull/8002",
"description": "Typed array slices are handled correctly now."
},
{
"version": "v6.1.0, v4.5.0",
"pr-url": "https://github.com/nodejs/node/pull/6432",
"description": "Objects with circular references can be used as inputs now."
},
{
"version": "v5.10.1, v4.4.3",
"pr-url": "https://github.com/nodejs/node/pull/5910",
"description": "Handle non-`Uint8Array` typed arrays correctly."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`actual` {any}",
"name": "actual",
"type": "any"
},
{
"textRaw": "`expected` {any}",
"name": "expected",
"type": "any"
},
{
"textRaw": "`message` {string|Error}",
"name": "message",
"type": "string|Error",
"optional": true
}
]
}
],
"desc": "Strict mode
\nAn alias of assert.notDeepStrictEqual()
.
Legacy mode
\n\n\nStability: 0 - Deprecated: Use
\nassert.notDeepStrictEqual()
instead.
Tests for any deep inequality. Opposite of assert.deepEqual()
.
const assert = require('assert');\n\nconst obj1 = {\n a: {\n b: 1\n }\n};\nconst obj2 = {\n a: {\n b: 2\n }\n};\nconst obj3 = {\n a: {\n b: 1\n }\n};\nconst obj4 = Object.create(obj1);\n\nassert.notDeepEqual(obj1, obj1);\n// AssertionError: { a: { b: 1 } } notDeepEqual { a: { b: 1 } }\n\nassert.notDeepEqual(obj1, obj2);\n// OK\n\nassert.notDeepEqual(obj1, obj3);\n// AssertionError: { a: { b: 1 } } notDeepEqual { a: { b: 1 } }\n\nassert.notDeepEqual(obj1, obj4);\n// OK\n
\nIf the values are deeply equal, an AssertionError
is thrown with a message
\nproperty set equal to the value of the message
parameter. If the message
\nparameter is undefined, a default error message is assigned. If the message
\nparameter is an instance of an Error
then it will be thrown instead of the\nAssertionError
.
Tests for deep strict inequality. Opposite of assert.deepStrictEqual()
.
const assert = require('assert').strict;\n\nassert.notDeepStrictEqual({ a: 1 }, { a: '1' });\n// OK\n
\nIf the values are deeply and strictly equal, an AssertionError
is thrown with\na message
property set equal to the value of the message
parameter. If the\nmessage
parameter is undefined, a default error message is assigned. If the\nmessage
parameter is an instance of an Error
then it will be thrown\ninstead of the AssertionError
.
Strict mode
\nAn alias of assert.notStrictEqual()
.
Legacy mode
\n\n\nStability: 0 - Deprecated: Use
\nassert.notStrictEqual()
instead.
Tests shallow, coercive inequality with the Abstract Equality Comparison\n( !=
).
const assert = require('assert');\n\nassert.notEqual(1, 2);\n// OK\n\nassert.notEqual(1, 1);\n// AssertionError: 1 != 1\n\nassert.notEqual(1, '1');\n// AssertionError: 1 != '1'\n
\nIf the values are equal, an AssertionError
is thrown with a message
property\nset equal to the value of the message
parameter. If the message
parameter is\nundefined, a default error message is assigned. If the message
parameter is an\ninstance of an Error
then it will be thrown instead of the\nAssertionError
.
Tests strict inequality between the actual
and expected
parameters as\ndetermined by the SameValue Comparison.
const assert = require('assert').strict;\n\nassert.notStrictEqual(1, 2);\n// OK\n\nassert.notStrictEqual(1, 1);\n// AssertionError [ERR_ASSERTION]: Expected \"actual\" to be strictly unequal to:\n//\n// 1\n\nassert.notStrictEqual(1, '1');\n// OK\n
\nIf the values are strictly equal, an AssertionError
is thrown with a message
\nproperty set equal to the value of the message
parameter. If the message
\nparameter is undefined, a default error message is assigned. If the message
\nparameter is an instance of an Error
then it will be thrown instead of the\nAssertionError
.
Tests if value
is truthy. It is equivalent to\nassert.equal(!!value, true, message)
.
If value
is not truthy, an AssertionError
is thrown with a message
\nproperty set equal to the value of the message
parameter. If the message
\nparameter is undefined
, a default error message is assigned. If the message
\nparameter is an instance of an Error
then it will be thrown instead of the\nAssertionError
.\nIf no arguments are passed in at all message
will be set to the string:\n'No value argument passed to `assert.ok()`'
.
Be aware that in the repl
the error message will be different to the one\nthrown in a file! See below for further details.
const assert = require('assert').strict;\n\nassert.ok(true);\n// OK\nassert.ok(1);\n// OK\n\nassert.ok();\n// AssertionError: No value argument passed to `assert.ok()`\n\nassert.ok(false, 'it\\'s false');\n// AssertionError: it's false\n\n// In the repl:\nassert.ok(typeof 123 === 'string');\n// AssertionError: false == true\n\n// In a file (e.g. test.js):\nassert.ok(typeof 123 === 'string');\n// AssertionError: The expression evaluated to a falsy value:\n//\n// assert.ok(typeof 123 === 'string')\n\nassert.ok(false);\n// AssertionError: The expression evaluated to a falsy value:\n//\n// assert.ok(false)\n\nassert.ok(0);\n// AssertionError: The expression evaluated to a falsy value:\n//\n// assert.ok(0)\n\n// Using `assert()` works the same:\nassert(0);\n// AssertionError: The expression evaluated to a falsy value:\n//\n// assert(0)\n
"
},
{
"textRaw": "assert.rejects(asyncFn[, error][, message])",
"type": "method",
"name": "rejects",
"meta": {
"added": [
"v10.0.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`asyncFn` {Function|Promise}",
"name": "asyncFn",
"type": "Function|Promise"
},
{
"textRaw": "`error` {RegExp|Function|Object|Error}",
"name": "error",
"type": "RegExp|Function|Object|Error",
"optional": true
},
{
"textRaw": "`message` {string}",
"name": "message",
"type": "string",
"optional": true
}
]
}
],
"desc": "Awaits the asyncFn
promise or, if asyncFn
is a function, immediately\ncalls the function and awaits the returned promise to complete. It will then\ncheck that the promise is rejected.
If asyncFn
is a function and it throws an error synchronously,\nassert.rejects()
will return a rejected Promise
with that error. If the\nfunction does not return a promise, assert.rejects()
will return a rejected\nPromise
with an ERR_INVALID_RETURN_VALUE
error. In both cases the error\nhandler is skipped.
Besides the async nature to await the completion behaves identically to\nassert.throws()
.
If specified, error
can be a Class
, RegExp
, a validation function,\nan object where each property will be tested for, or an instance of error where\neach property will be tested for including the non-enumerable message
and\nname
properties.
If specified, message
will be the message provided by the AssertionError
if\nthe asyncFn
fails to reject.
(async () => {\n await assert.rejects(\n async () => {\n throw new TypeError('Wrong value');\n },\n {\n name: 'TypeError',\n message: 'Wrong value'\n }\n );\n})();\n
\nassert.rejects(\n Promise.reject(new Error('Wrong value')),\n Error\n).then(() => {\n // ...\n});\n
\nNote that error
cannot be a string. If a string is provided as the second\nargument, then error
is assumed to be omitted and the string will be used for\nmessage
instead. This can lead to easy-to-miss mistakes. Please read the\nexample in assert.throws()
carefully if using a string as the second\nargument gets considered.
Tests strict equality between the actual
and expected
parameters as\ndetermined by the SameValue Comparison.
const assert = require('assert').strict;\n\nassert.strictEqual(1, 2);\n// AssertionError [ERR_ASSERTION]: Expected inputs to be strictly equal:\n//\n// 1 !== 2\n\nassert.strictEqual(1, 1);\n// OK\n\nassert.strictEqual('Hello foobar', 'Hello World!');\n// AssertionError [ERR_ASSERTION]: Expected inputs to be strictly equal:\n// + actual - expected\n//\n// + 'Hello foobar'\n// - 'Hello World!'\n// ^\n
\nIf the values are not strictly equal, an AssertionError
is thrown with a\nmessage
property set equal to the value of the message
parameter. If the\nmessage
parameter is undefined, a default error message is assigned. If the\nmessage
parameter is an instance of an Error
then it will be thrown\ninstead of the AssertionError
.
Expects the function fn
to throw an error.
If specified, error
can be a Class
, RegExp
, a validation function,\na validation object where each property will be tested for strict deep equality,\nor an instance of error where each property will be tested for strict deep\nequality including the non-enumerable message
and name
properties. When\nusing an object, it is also possible to use a regular expression, when\nvalidating against a string property. See below for examples.
If specified, message
will be appended to the message provided by the\nAssertionError
if the fn
call fails to throw or in case the error validation\nfails.
Custom validation object/error instance:
\nconst err = new TypeError('Wrong value');\nerr.code = 404;\nerr.foo = 'bar';\nerr.info = {\n nested: true,\n baz: 'text'\n};\nerr.reg = /abc/i;\n\nassert.throws(\n () => {\n throw err;\n },\n {\n name: 'TypeError',\n message: 'Wrong value',\n info: {\n nested: true,\n baz: 'text'\n }\n // Note that only properties on the validation object will be tested for.\n // Using nested objects requires all properties to be present. Otherwise\n // the validation is going to fail.\n }\n);\n\n// Using regular expressions to validate error properties:\nassert.throws(\n () => {\n throw err;\n },\n {\n // The `name` and `message` properties are strings and using regular\n // expressions on those will match against the string. If they fail, an\n // error is thrown.\n name: /^TypeError$/,\n message: /Wrong/,\n foo: 'bar',\n info: {\n nested: true,\n // It is not possible to use regular expressions for nested properties!\n baz: 'text'\n },\n // The `reg` property contains a regular expression and only if the\n // validation object contains an identical regular expression, it is going\n // to pass.\n reg: /abc/i\n }\n);\n\n// Fails due to the different `message` and `name` properties:\nassert.throws(\n () => {\n const otherErr = new Error('Not found');\n otherErr.code = 404;\n throw otherErr;\n },\n err // This tests for `message`, `name` and `code`.\n);\n
\nValidate instanceof using constructor:
\nassert.throws(\n () => {\n throw new Error('Wrong value');\n },\n Error\n);\n
\nValidate error message using RegExp
:
Using a regular expression runs .toString
on the error object, and will\ntherefore also include the error name.
assert.throws(\n () => {\n throw new Error('Wrong value');\n },\n /^Error: Wrong value$/\n);\n
\nCustom error validation:
\nassert.throws(\n () => {\n throw new Error('Wrong value');\n },\n function(err) {\n if ((err instanceof Error) && /value/.test(err)) {\n return true;\n }\n },\n 'unexpected error'\n);\n
\nNote that error
cannot be a string. If a string is provided as the second\nargument, then error
is assumed to be omitted and the string will be used for\nmessage
instead. This can lead to easy-to-miss mistakes. Using the same\nmessage as the thrown error message is going to result in an\nERR_AMBIGUOUS_ARGUMENT
error. Please read the example below carefully if using\na string as the second argument gets considered:
function throwingFirst() {\n throw new Error('First');\n}\nfunction throwingSecond() {\n throw new Error('Second');\n}\nfunction notThrowing() {}\n\n// The second argument is a string and the input function threw an Error.\n// The first case will not throw as it does not match for the error message\n// thrown by the input function!\nassert.throws(throwingFirst, 'Second');\n// In the next example the message has no benefit over the message from the\n// error and since it is not clear if the user intended to actually match\n// against the error message, Node.js throws an `ERR_AMBIGUOUS_ARGUMENT` error.\nassert.throws(throwingSecond, 'Second');\n// TypeError [ERR_AMBIGUOUS_ARGUMENT]\n\n// The string is only used (as message) in case the function does not throw:\nassert.throws(notThrowing, 'Second');\n// AssertionError [ERR_ASSERTION]: Missing expected exception: Second\n\n// If it was intended to match for the error message do this instead:\n// It does not throw because the error messages match.\nassert.throws(throwingSecond, /Second$/);\n\n// If the error message does not match, the error from within the function is\n// not caught.\nassert.throws(throwingFirst, /Second$/);\n// Error: First\n// at throwingFirst (repl:2:9)\n
\nDue to the confusing notation, it is recommended not to use a string as the\nsecond argument. This might lead to difficult-to-spot errors.
" } ], "type": "module", "displayName": "Assert" } ] }