Assert
目录
- Strict assertion mode
- Legacy assertion mode
- Class: assert.AssertionError
- Class: assert.CallTracker
- assert(value[, message])
- assert.deepEqual(actual, expected[, message])
- assert.deepStrictEqual(actual, expected[, message])
- assert.doesNotMatch(string, regexp[, message])
- assert.doesNotReject(asyncFn[, error][, message])
- assert.doesNotThrow(fn[, error][, message])
- assert.equal(actual, expected[, message])
- assert.fail([message])
- assert.fail(actual, expected[, message[, operator[, stackStartFn]]])
- assert.ifError(value)
- assert.match(string, regexp[, message])
- assert.notDeepEqual(actual, expected[, message])
- assert.notDeepStrictEqual(actual, expected[, message])
- assert.notEqual(actual, expected[, message])
- assert.notStrictEqual(actual, expected[, message])
- assert.ok(value[, message])
- assert.rejects(asyncFn[, error][, message])
- assert.snapshot(value, name)
- assert.strictEqual(actual, expected[, message])
- assert.throws(fn[, error][, message])
Added in: v0.1.21
源代码: lib/assert.js
The node:assert
module provides a set of assertion functions for verifying
invariants.
Strict assertion mode
历史
版本 | 更改 |
---|---|
v15.0.0 | Exposed as `require('node:assert/strict')`. |
v13.9.0, v12.16.2 | Changed "strict mode" to "strict assertion mode" and "legacy mode" to "legacy assertion mode" to avoid confusion with the more usual meaning of "strict mode". |
v9.9.0 | Added error diffs to the strict assertion mode. |
v9.9.0 | Added strict assertion mode to the assert module. |
v9.9.0 | Added in: v9.9.0 |
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:
MJS
CJS
MJS
CJS
Example error diff:
MJS
CJS
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:
MJS
CJS
Legacy assertion mode may have surprising results, especially when using
assert.deepEqual()
:
CJS
C assert.AssertionError
- Extends:
errors.Error
Indicates the failure of an assertion. All errors thrown by the node:assert
module will be instances of the AssertionError
class.
M 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
Theactual
property on the error instance.expected
any
Theexpected
property on the error instance.operator
string
Theoperator
property on the error instance.stackStartFn
Function
If provided, the generated stack trace omits frames before this function.
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 theactual
argument for methods such asassert.strictEqual()
.expected
any
Set to theexpected
value for methods such asassert.strictEqual()
.generatedMessage
boolean
Indicates if the message was auto-generated (true
) or not.code
string
Value is alwaysERR_ASSERTION
to show that the error is an assertion error.operator
string
Set to the passed in operator value.
MJS
CJS
C assert.CallTracker
Added in: v14.2.0, v12.19.0
This feature is currently experimental and behavior might still change.
M new assert.CallTracker()
Added in: v14.2.0, v12.19.0
Creates a new CallTracker
object which can be used to track if functions
were called a specific number of times. The tracker.verify()
must be called
for the verification to take place. The usual pattern would be to call it in a
process.on('exit')
handler.
MJS
CJS
M tracker.calls([fn][, exact])
Added in: v14.2.0, v12.19.0
The wrapper function is expected to be called exactly exact
times. If the
function has not been called exactly exact
times when
tracker.verify()
is called, then tracker.verify()
will throw an
error.
MJS
CJS
M tracker.getCalls(fn)
Added in: v18.8.0, v16.18.0
MJS
CJS
M tracker.report()
Added in: v14.2.0, v12.19.0
- Returns:
Array
of objects containing information about the wrapper functions returned bytracker.calls()
. - Object
Object
The arrays contains information about the expected and actual number of calls of the functions that have not been called the expected number of times.
MJS
CJS
M tracker.reset([fn])
Added in: v18.8.0, v16.18.0
fn
Function
a tracked function to reset.
reset calls of the call tracker. if a tracked function is passed as an argument, the calls will be reset for it. if no arguments are passed, all tracked functions will be reset
MJS
CJS
M tracker.verify()
Added in: v14.2.0, v12.19.0
Iterates through the list of functions passed to
tracker.calls()
and will throw an error for functions that
have not been called the expected number of times.
MJS
CJS
M assert(value[, message])
Added in: v0.5.9
An alias of assert.ok()
.
M assert.deepEqual(actual, expected[, message])
历史
版本 | 更改 |
---|---|
v18.0.0 | Regular expressions lastIndex property is now compared as well. |
v16.0.0, v14.18.0 | In Legacy assertion mode, changed status from Deprecated to Legacy. |
v14.0.0 | NaN is now treated as being identical if both sides are NaN. |
v12.0.0 | The type tags are now properly compared and there are a couple minor comparison adjustments to make the check less surprising. |
v9.0.0 | The `Error` names and messages are now properly compared. |
v8.0.0 | The `Set` and `Map` content is also compared. |
v6.4.0, v4.7.1 | Typed array slices are handled correctly now. |
v6.1.0, v4.5.0 | Objects with circular references can be used as inputs now. |
v5.10.1, v4.4.3 | Handle non-`Uint8Array` typed arrays correctly. |
v0.1.21 | Added in: v0.1.21 |
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 ofNaN
. It is treated as being identical in case both sides areNaN
. - Type tags of objects should be the same.
- Only enumerable "own" properties are considered.
Error
names and messages 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 andSet
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
andWeakSet
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.
MJS
CJS
"Deep" equality means that the enumerable "own" properties of child objects are evaluated also:
MJS
CJS
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 an Error
then it will be thrown instead of the
AssertionError
.
M assert.deepStrictEqual(actual, expected[, message])
历史
版本 | 更改 |
---|---|
v18.0.0 | Regular expressions lastIndex property is now compared as well. |
v9.0.0 | Enumerable symbol properties are now compared. |
v9.0.0 | The `NaN` is now compared using the [SameValueZero](https://tc39.github.io/ecma262/#sec-samevaluezero) comparison. |
v8.5.0 | The `Error` names and messages are now properly compared. |
v8.0.0 | The `Set` and `Map` content is also compared. |
v6.4.0, v4.7.1 | Typed array slices are handled correctly now. |
v6.1.0 | Objects with circular references can be used as inputs now. |
v5.10.1, v4.4.3 | Handle non-`Uint8Array` typed arrays correctly. |
v1.2.0 | Added in: v1.2.0 |
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 and messages are always compared, even if these are not enumerable properties.- 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 andSet
items are compared unordered.- Recursion stops when both sides differ or both sides encounter a circular reference.
WeakMap
andWeakSet
comparison does not rely on their values. See below for further details.RegExp
lastIndex, flags, and source are always compared, even if these are not enumerable properties.
MJS
CJS
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 an Error
then it will be thrown instead of the
AssertionError
.
M assert.doesNotMatch(string, regexp[, message])
历史
版本 | 更改 |
---|---|
v16.0.0 | This API is no longer experimental. |
v13.6.0, v12.16.0 | Added in: v13.6.0, v12.16.0 |
Expects the string
input not to match the regular expression.
MJS
CJS
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 an Error
then it will be thrown instead of the
AssertionError
.
M 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()
.
MJS
CJS
MJS
CJS
M assert.doesNotThrow(fn[, error][, message])
历史
版本 | 更改 |
---|---|
v5.11.0, v4.4.5 | The `message` parameter is respected now. |
v4.2.0 | The `error` parameter can now be an arrow function. |
v0.1.21 | Added in: v0.1.21 |
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:
MJS
CJS
However, the following will result in an AssertionError
with the message
'Got unwanted exception...':
MJS
CJS
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:
MJS
CJS
M assert.equal(actual, expected[, message])
历史
版本 | 更改 |
---|---|
v16.0.0, v14.18.0 | In Legacy assertion mode, changed status from Deprecated to Legacy. |
v14.0.0 | NaN is now treated as being identical if both sides are NaN. |
v0.1.21 | Added in: v0.1.21 |
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
.
MJS
CJS
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 an Error
then it will be thrown instead of the
AssertionError
.
M 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 an Error
then
it will be thrown instead of the AssertionError
.
MJS
CJS
Using assert.fail()
with more than two arguments is possible but deprecated.
See below for further details.
M assert.fail(actual, expected[, message[, operator[, stackStartFn]]])
历史
版本 | 更改 |
---|---|
v10.0.0 | Calling `assert.fail()` with more than one argument is deprecated and emits a warning. |
v0.1.21 | Added in: v0.1.21 |
actual
any
expected
any
message
string
|Error
operator
string
Default:'!='
stackStartFn
Function
Default:assert.fail
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.
MJS
CJS
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:
MJS
CJS
M assert.ifError(value)
历史
版本 | 更改 |
---|---|
v10.0.0 | Instead of throwing the original error it is now wrapped into an [`AssertionError`][] that contains the full stack trace. |
v10.0.0 | Value may now only be `undefined` or `null`. Before all falsy values were handled the same as `null` and did not throw. |
v0.1.97 | Added in: v0.1.97 |
value
any
Throws value
if value
is not undefined
or null
. This is useful when
testing the error
argument in callbacks. The stack trace contains all frames
from the error passed to ifError()
including the potential new frames for
ifError()
itself.
MJS
CJS
M assert.match(string, regexp[, message])
历史
版本 | 更改 |
---|---|
v16.0.0 | This API is no longer experimental. |
v13.6.0, v12.16.0 | Added in: v13.6.0, v12.16.0 |
Expects the string
input to match the regular expression.
MJS
CJS
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 an Error
then it will be thrown instead of the
AssertionError
.
M assert.notDeepEqual(actual, expected[, message])
历史
版本 | 更改 |
---|---|
v16.0.0, v14.18.0 | In Legacy assertion mode, changed status from Deprecated to Legacy. |
v14.0.0 | NaN is now treated as being identical if both sides are NaN. |
v9.0.0 | The `Error` names and messages are now properly compared. |
v8.0.0 | The `Set` and `Map` content is also compared. |
v6.4.0, v4.7.1 | Typed array slices are handled correctly now. |
v6.1.0, v4.5.0 | Objects with circular references can be used as inputs now. |
v5.10.1, v4.4.3 | Handle non-`Uint8Array` typed arrays correctly. |
v0.1.21 | Added in: v0.1.21 |
Strict assertion mode
An alias of assert.notDeepStrictEqual()
.
Legacy assertion mode
Tests for any deep inequality. Opposite of assert.deepEqual()
.
MJS
CJS
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 an Error
then it will be thrown
instead of the AssertionError
.
M assert.notDeepStrictEqual(actual, expected[, message])
历史
版本 | 更改 |
---|---|
v9.0.0 | The `-0` and `+0` are not considered equal anymore. |
v9.0.0 | The `NaN` is now compared using the [SameValueZero](https://tc39.github.io/ecma262/#sec-samevaluezero) comparison. |
v9.0.0 | The `Error` names and messages are now properly compared. |
v8.0.0 | The `Set` and `Map` content is also compared. |
v6.4.0, v4.7.1 | Typed array slices are handled correctly now. |
v6.1.0 | Objects with circular references can be used as inputs now. |
v5.10.1, v4.4.3 | Handle non-`Uint8Array` typed arrays correctly. |
v1.2.0 | Added in: v1.2.0 |
Tests for deep strict inequality. Opposite of assert.deepStrictEqual()
.
MJS
CJS
If the values are deeply and 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 an Error
then it will be thrown
instead of the AssertionError
.
M assert.notEqual(actual, expected[, message])
历史
版本 | 更改 |
---|---|
v16.0.0, v14.18.0 | In Legacy assertion mode, changed status from Deprecated to Legacy. |
v14.0.0 | NaN is now treated as being identical if both sides are NaN. |
v0.1.21 | Added in: v0.1.21 |
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
.
MJS
CJS
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 an Error
then it will be thrown instead of the
AssertionError
.
M assert.notStrictEqual(actual, expected[, message])
历史
版本 | 更改 |
---|---|
v10.0.0 | Used comparison changed from Strict Equality to `Object.is()`. |
v0.1.21 | Added in: v0.1.21 |
Tests strict inequality between the actual
and expected
parameters as
determined by Object.is()
.
MJS
CJS
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 an Error
then it will be thrown
instead of the AssertionError
.
M assert.ok(value[, message])
历史
版本 | 更改 |
---|---|
v10.0.0 | The `assert.ok()` (no arguments) will now use a predefined error message. |
v0.1.21 | Added in: v0.1.21 |
Tests if value
is truthy. It is equivalent to
assert.equal(!!value, true, message)
.
If value
is not truthy, 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 an Error
then it will be thrown instead of the
AssertionError
.
If no arguments are passed in at all message
will be set to the string:
'No value argument passed to `assert.ok()`'
.
Be aware that in the repl
the error message will be different to the one
thrown in a file! See below for further details.
MJS
CJS
MJS
CJS
M 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.
MJS
CJS
MJS
CJS
MJS
CJS
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.
M assert.snapshot(value, name)
Added in: v18.8.0
Reads the name
snapshot from a file and compares value
to the snapshot.
value
is serialized with util.inspect()
. If the value is not strictly
equal to the snapshot, assert.snapshot()
returns a rejected Promise
with an
AssertionError
.
The snapshot filename uses the same basename as the application's main
entrypoint with a .snapshot
extension. If the snapshot file does not exist,
it is created. The --update-assert-snapshot
command line flag can be used
to force the update of an existing snapshot.
MJS
CJS
M assert.strictEqual(actual, expected[, message])
历史
版本 | 更改 |
---|---|
v10.0.0 | Used comparison changed from Strict Equality to `Object.is()`. |
v0.1.21 | Added in: v0.1.21 |
Tests strict equality between the actual
and expected
parameters as
determined by Object.is()
.
MJS
CJS
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 an Error
then it will be thrown
instead of the AssertionError
.
M assert.throws(fn[, error][, message])
历史
版本 | 更改 |
---|---|
v10.2.0 | The `error` parameter can be an object containing regular expressions now. |
v9.9.0 | The `error` parameter can now be an object as well. |
v4.2.0 | The `error` parameter can now be an arrow function. |
v0.1.21 | Added in: v0.1.21 |
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:
MJS
CJS
Validate instanceof using constructor:
MJS
CJS
Validate error message using RegExp
:
Using a regular expression runs .toString
on the error object, and will
therefore also include the error name.
MJS
CJS
Custom error validation:
The function must return true
to indicate all internal validations passed.
It will otherwise fail with an AssertionError
.
MJS
CJS
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:
MJS
CJS
Due to the confusing error-prone notation, avoid a string as the second argument.