消息参数语义


🌐 Message parameter semantics

对于接受可选 message 参数的断言方法,消息可以以以下形式之一提供:

🌐 For assertion methods that accept an optional message parameter, the message may be provided in one of the following forms:

  • string:按原样使用。如果在 message 字符串之后提供了额外的参数,它们将被视为类似 printf 的替换(参见 util.format())。
  • 错误:如果将 Error 实例作为 message 提供,该错误会直接抛出,而不是抛出 AssertionError
  • 函数:形式为 (actual, expected) => string 的函数。它仅在断言失败时调用,并应返回一个字符串以用作错误消息。非字符串返回值将被忽略,并使用默认消息。

如果在传递 Error 或作为 message 的函数时附加了其他参数,该调用将被 ERR_AMBIGUOUS_ARGUMENT 拒绝。

🌐 If additional arguments are passed along with an Error or a function as message, the call is rejected with ERR_AMBIGUOUS_ARGUMENT.

如果第一个项既不是字符串 Error,也不是函数,则抛出 ERR_INVALID_ARG_TYPE

🌐 If the first item is neither a string, Error, nor function, ERR_INVALID_ARG_TYPE is thrown.

使用严格断言模式:

🌐 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]);
// AssertionError: Expected inputs to be strictly deep-equal:
// + actual - expected ... Lines skipped
//
//   [
//     [
// ...
//       2,
// +     3
// -     '3'
//     ],
// ...
//     5
//   ]const assert = require('node:assert/strict');

assert.deepEqual([[[1, 2, 3]], 4, 5], [[[1, 2, '3']], 4, 5]);
// AssertionError: Expected inputs to be strictly deep-equal:
// + actual - expected ... Lines skipped
//
//   [
//     [
// ...
//       2,
// +     3
// -     '3'
//     ],
// ...
//     5
//   ]

要停用颜色,请使用 NO_COLORNODE_DISABLE_COLORS 环境变量。这也会在 REPL 中停用颜色。有关终端环境中颜色支持的更多信息,请读取 tty getColorDepth() 文档。

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