严格断言模式


在严格断言模式下,非严格方法的行为与其对应的严格方法相同。 例如,assert.deepEqual() 的行为类似于 assert.deepStrictEqual()

在严格断言模式下,对象的错误消息显示差异。 在旧版断言模式下,对象的错误消息显示对象,通常被截断。

使用严格断言模式:

const assert = require('assert').strict;

错误差异的示例:

const assert = require('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 环境变量。 这也将停用交互式解释器中的颜色。 有关终端环境中颜色支持的更多信息,请阅读终端 getColorDepth() 文档。

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:

const assert = require('assert').strict;

Example error diff:

const assert = require('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
//   ]

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.