home / documentation / v16 / assert

Assert

目录

Added in: v0.1.21

稳定性: 2 - Stable

The node:assert module provides a set of assertion functions for verifying invariants.

Strict assertion mode

历史
版本更改
v15.0.0Exposed as `require('node:assert/strict')`.
v13.9.0, v12.16.2Changed "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.0Added error diffs to the strict assertion mode.
v9.9.0Added strict assertion mode to the assert module.
v9.9.0Added 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

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

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

C assert.CallTracker

Added in: v14.2.0, v12.19.0

稳定性: 1 - Experimental

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

  • fn Function.

  • Returns: Array with all the calls to a tracked function.

  • Object Object

    • thisArg Object
    • arguments Array the arguments passed to the tracked function
MJS
CJS

M tracker.report()

Added in: v14.2.0, v12.19.0

  • Returns: Array of objects containing information about the wrapper functions returned by tracker.calls().
  • Object Object
    • message string
    • actual number The actual number of times the function was called.
    • expected number The number of times the function was expected to be called.
    • operator string The name of the function that is wrapped.
    • stack Object A stack trace of the function.

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

  • value any The input that is checked for being truthy.
  • message string | Error

An alias of assert.ok().

M assert.deepEqual(actual, expected[, message])

历史
版本更改
v16.0.0In Legacy assertion mode, changed status from Deprecated to Legacy.
v14.0.0NaN is now treated as being identical if both sides are NaN.
v12.0.0The type tags are now properly compared and there are a couple minor comparison adjustments to make the check less surprising.
v9.0.0The `Error` names and messages are now properly compared.
v8.0.0The `Set` and `Map` content is also compared.
v6.4.0, v4.7.1Typed array slices are handled correctly now.
v6.1.0, v4.5.0Objects with circular references can be used as inputs now.
v5.10.1, v4.4.3Handle non-`Uint8Array` typed arrays correctly.
v0.1.21Added in: v0.1.21

Strict assertion mode

An alias of assert.deepStrictEqual().

Legacy assertion mode

稳定性: 3 - Legacy: Use `assert.deepStrictEqual()` instead.

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

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])

历史
版本更改
v9.0.0Enumerable symbol properties are now compared.
v9.0.0The `NaN` is now compared using the [SameValueZero](https://tc39.github.io/ecma262/#sec-samevaluezero) comparison.
v8.5.0The `Error` names and messages are now properly compared.
v8.0.0The `Set` and `Map` content is also compared.
v6.4.0, v4.7.1Typed array slices are handled correctly now.
v6.1.0Objects with circular references can be used as inputs now.
v5.10.1, v4.4.3Handle non-`Uint8Array` typed arrays correctly.
v1.2.0Added 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 and Set items are compared unordered.
  • Recursion stops when both sides differ or both sides encounter a circular reference.
  • WeakMap and WeakSet comparison does not rely on their values. See below for further details.
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.0This API is no longer experimental.
v13.6.0, v12.16.0Added 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.5The `message` parameter is respected now.
v4.2.0The `error` parameter can now be an arrow function.
v0.1.21Added 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.0In Legacy assertion mode, changed status from Deprecated to Legacy.
v14.0.0NaN is now treated as being identical if both sides are NaN.
v0.1.21Added in: v0.1.21

Strict assertion mode

An alias of assert.strictEqual().

Legacy assertion mode

稳定性: 3 - Legacy: Use `assert.strictEqual()` instead.

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.0Calling `assert.fail()` with more than one argument is deprecated and emits a warning.
v0.1.21Added in: v0.1.21
稳定性: 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.

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.0Instead of throwing the original error it is now wrapped into an [`AssertionError`][] that contains the full stack trace.
v10.0.0Value may now only be `undefined` or `null`. Before all falsy values were handled the same as `null` and did not throw.
v0.1.97Added in: v0.1.97

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.0This API is no longer experimental.
v13.6.0, v12.16.0Added 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.0In Legacy assertion mode, changed status from Deprecated to Legacy.
v14.0.0NaN is now treated as being identical if both sides are NaN.
v9.0.0The `Error` names and messages are now properly compared.
v8.0.0The `Set` and `Map` content is also compared.
v6.4.0, v4.7.1Typed array slices are handled correctly now.
v6.1.0, v4.5.0Objects with circular references can be used as inputs now.
v5.10.1, v4.4.3Handle non-`Uint8Array` typed arrays correctly.
v0.1.21Added in: v0.1.21

Strict assertion mode

An alias of assert.notDeepStrictEqual().

Legacy assertion mode

稳定性: 3 - Legacy: Use `assert.notDeepStrictEqual()` instead.

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.0The `-0` and `+0` are not considered equal anymore.
v9.0.0The `NaN` is now compared using the [SameValueZero](https://tc39.github.io/ecma262/#sec-samevaluezero) comparison.
v9.0.0The `Error` names and messages are now properly compared.
v8.0.0The `Set` and `Map` content is also compared.
v6.4.0, v4.7.1Typed array slices are handled correctly now.
v6.1.0Objects with circular references can be used as inputs now.
v5.10.1, v4.4.3Handle non-`Uint8Array` typed arrays correctly.
v1.2.0Added 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.0In Legacy assertion mode, changed status from Deprecated to Legacy.
v14.0.0NaN is now treated as being identical if both sides are NaN.
v0.1.21Added in: v0.1.21

Strict assertion mode

An alias of assert.notStrictEqual().

Legacy assertion mode

稳定性: 3 - Legacy: Use `assert.notStrictEqual()` instead.

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.0Used comparison changed from Strict Equality to `Object.is()`.
v0.1.21Added 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.0The `assert.ok()` (no arguments) will now use a predefined error message.
v0.1.21Added 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.strictEqual(actual, expected[, message])

历史
版本更改
v10.0.0Used comparison changed from Strict Equality to `Object.is()`.
v0.1.21Added 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.0The `error` parameter can be an object containing regular expressions now.
v9.9.0The `error` parameter can now be an object as well.
v4.2.0The `error` parameter can now be an arrow function.
v0.1.21Added 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.