源代码: lib/assert.js
assert 模块提供了一组用于验证不变量的断言函数。
在严格断言模式下,非严格方法的行为与其对应的严格方法相同。
例如,assert.deepEqual() 的行为类似于 assert.deepStrictEqual()。
在严格断言模式下,对象的错误消息显示差异。 在旧版断言模式下,对象的错误消息显示对象,通常被截断。
使用严格断言模式:
import { strict as assert } from 'assert';const assert = require('assert').strict;
import assert from 'assert/strict';const assert = require('assert/strict');
错误差异的示例:
import { strict as assert } from '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('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_COLOR 或 NODE_DISABLE_COLORS 环境变量。
这也将停用交互式解释器中的颜色。
有关终端环境中颜色支持的更多信息,请阅读终端 getColorDepth() 文档。
旧版断言模式在以下方法中使用 == 运算符:
要使用旧版断言模式:
import assert from 'assert';const assert = require('assert');
旧版断言模式可能会产生意外的结果,尤其是在使用 assert.deepEqual() 时:
// 注意:在旧版断言模式下这不会抛出 AssertionError!
assert.deepEqual(/a/gi, new Date());
表示断言的失败。
assert 模块抛出的所有错误都是 AssertionError 类的实例。
new assert.AssertionError(options)#options <Object>
message <string> 如果提供,则错误消息将设置为此值。actual <any> 错误实例上的 actual 属性。expected <any> 错误实例上的 expected 属性。operator <string> 错误实例上的 operator 属性。stackStartFn <Function> 如果提供,则生成的堆栈跟踪将省略此函数之前的帧。Error 的子类,表示断言的失败。
所有实例都包含内置的 Error 属性(message 和 name),以及:
actual <any> 对于 assert.strictEqual() 等方法,设置为 actual 参数。expected <any> 对于 assert.strictEqual() 等方法,设置为 expected 值。generatedMessage <boolean> 指示消息是否是自动生成的 (true)。code <string> 值始终为 ERR_ASSERTION,以表明该错误是断言错误。operator <string> 设置为传入的运算符值。import assert from 'assert';
// 生成 AssertionError,以便稍后比较错误信息:
const { message } = new assert.AssertionError({
actual: 1,
expected: 2,
operator: 'strictEqual'
});
// 验证错误的输出:
try {
assert.strictEqual(1, 2);
} catch (err) {
assert(err instanceof assert.AssertionError);
assert.strictEqual(err.message, message);
assert.strictEqual(err.name, 'AssertionError');
assert.strictEqual(err.actual, 1);
assert.strictEqual(err.expected, 2);
assert.strictEqual(err.code, 'ERR_ASSERTION');
assert.strictEqual(err.operator, 'strictEqual');
assert.strictEqual(err.generatedMessage, true);
}const assert = require('assert');
// 生成 AssertionError,以便稍后比较错误信息:
const { message } = new assert.AssertionError({
actual: 1,
expected: 2,
operator: 'strictEqual'
});
// 验证错误的输出:
try {
assert.strictEqual(1, 2);
} catch (err) {
assert(err instanceof assert.AssertionError);
assert.strictEqual(err.message, message);
assert.strictEqual(err.name, 'AssertionError');
assert.strictEqual(err.actual, 1);
assert.strictEqual(err.expected, 2);
assert.strictEqual(err.code, 'ERR_ASSERTION');
assert.strictEqual(err.operator, 'strictEqual');
assert.strictEqual(err.generatedMessage, true);
}
assert.CallTracker 类#此功能目前处于实验阶段,行为可能仍会发生变化。
new assert.CallTracker()#创建新的 CallTracker 对象,其可用于跟踪函数是否被调用了特定次数。
必须调用 tracker.verify() 才能进行验证。
通常的模式是在 process.on('exit') 句柄中调用。
import assert from 'assert';
import process from 'process';
const tracker = new assert.CallTracker();
function func() {}
// callfunc() 必须在 tracker.verify() 之前恰好被调用 1 次。
const callsfunc = tracker.calls(func, 1);
callsfunc();
// 调用 tracker.verify() 并验证是否所有 tracker.calls() 函数都已被准确调用。
process.on('exit', () => {
tracker.verify();
});const assert = require('assert');
const tracker = new assert.CallTracker();
function func() {}
// callfunc() 必须在 tracker.verify() 之前恰好被调用 1 次。
const callsfunc = tracker.calls(func, 1);
callsfunc();
// 调用 tracker.verify() 并验证是否所有 tracker.calls() 函数都已被准确调用。
process.on('exit', () => {
tracker.verify();
});
tracker.calls([fn][, exact])#fn <Function> 默认值: 无操作的函数。exact <number> 默认值: 1。fn。预计封装函数将被精确调用 exact 次。
如果在调用 tracker.verify() 时函数没有被精确调用 exact 次,那么 tracker.verify() 将抛出错误。
import assert from 'assert';
// 创建调用跟踪器。
const tracker = new assert.CallTracker();
function func() {}
// 返回封装 func() 的函数,其必须在 tracker.verify() 之前调用准确次数。
const callsfunc = tracker.calls(func);const assert = require('assert');
// 创建调用跟踪器。
const tracker = new assert.CallTracker();
function func() {}
// 返回封装 func() 的函数,其必须在 tracker.verify() 之前调用准确次数。
const callsfunc = tracker.calls(func);
tracker.report()#tracker.calls() 返回的封装函数的信息的对象的数组。数组包含有关未调用预期次数的函数的预期和实际调用次数的信息。
import assert from 'assert';
// 创建调用跟踪器。
const tracker = new assert.CallTracker();
function func() {}
function foo() {}
// 返回封装 func() 的函数,其必须在 tracker.verify() 之前调用准确次数。
const callsfunc = tracker.calls(func, 2);
// 返回包含 callfunc() 信息的数组()
tracker.report();
// [
// {
// message: 'Expected the func function to be executed 2 time(s) but was
// executed 0 time(s).',
// actual: 0,
// expected: 2,
// operator: 'func',
// stack: stack trace
// }
// ]const assert = require('assert');
// 创建调用跟踪器。
const tracker = new assert.CallTracker();
function func() {}
function foo() {}
// 返回封装 func() 的函数,其必须在 tracker.verify() 之前调用准确次数。
const callsfunc = tracker.calls(func, 2);
// 返回包含 callfunc() 信息的数组()
tracker.report();
// [
// {
// message: 'Expected the func function to be executed 2 time(s) but was
// executed 0 time(s).',
// actual: 0,
// expected: 2,
// operator: 'func',
// stack: stack trace
// }
// ]
tracker.verify()#遍历传给 tracker.calls() 的函数列表,对于未按预期调用次数的函数将抛出错误。
import assert from 'assert';
// 创建调用跟踪器。
const tracker = new assert.CallTracker();
function func() {}
// 返回封装 func() 的函数,其必须在 tracker.verify() 之前调用准确次数。
const callsfunc = tracker.calls(func, 2);
callsfunc();
// 会抛出错误,因为 callfunc() 只被调用了一次。
tracker.verify();const assert = require('assert');
// 创建调用跟踪器。
const tracker = new assert.CallTracker();
function func() {}
// 返回封装 func() 的函数,其必须在 tracker.verify() 之前调用准确次数。
const callsfunc = tracker.calls(func, 2);
callsfunc();
// 会抛出错误,因为 callfunc() 只被调用了一次。
tracker.verify();
assert(value[, message])#assert.ok() 的别名。
assert.deepEqual(actual, expected[, message])#严格断言模式
旧版断言模式
assert.deepStrictEqual() 。测试 actual 和 expected 参数之间的深度相等。
考虑使用 assert.deepStrictEqual() 代替。
assert.deepEqual() 可能产生意外的结果。
深度相等意味着子对象的可枚举"自有"属性也按照以下规则递归地评估。
NaN 外,原始值使用 == 运算符进行比较。
如果双方都是 NaN,则视为相同。Error 名称和消息总是被比较,即使它们不是可枚举的属性。Object 属性是无序比较的。Map 键和 Set 项是无序比较的。[[Prototype]]。Symbol 属性。WeakMap 和 WeakSet 的比较不依赖于它们的值。以下示例不会抛出 AssertionError,因为使用 == 运算符比较原始值。
import assert from 'assert';
// 注意:这不会抛出 AssertionError!
assert.deepEqual('+00000000', false);const assert = require('assert');
// 注意:这不会抛出 AssertionError!
assert.deepEqual('+00000000', false);
“深度”相等意味着子对象的可枚举"自有"属性也被评估:
import assert from 'assert';
const obj1 = {
a: {
b: 1
}
};
const obj2 = {
a: {
b: 2
}
};
const obj3 = {
a: {
b: 1
}
};
const obj4 = Object.create(obj1);
assert.deepEqual(obj1, obj1);
// OK
// b 的值不同:
assert.deepEqual(obj1, obj2);
// AssertionError: { a: { b: 1 } } deepEqual { a: { b: 2 } }
assert.deepEqual(obj1, obj3);
// OK
// 原型被忽略:
assert.deepEqual(obj1, obj4);
// AssertionError: { a: { b: 1 } } deepEqual {}const assert = require('assert');
const obj1 = {
a: {
b: 1
}
};
const obj2 = {
a: {
b: 2
}
};
const obj3 = {
a: {
b: 1
}
};
const obj4 = Object.create(obj1);
assert.deepEqual(obj1, obj1);
// OK
// b 的值不同:
assert.deepEqual(obj1, obj2);
// AssertionError: { a: { b: 1 } } deepEqual { a: { b: 2 } }
assert.deepEqual(obj1, obj3);
// OK
// 原型被忽略:
assert.deepEqual(obj1, obj4);
// AssertionError: { a: { b: 1 } } deepEqual {}
如果值不相等,则抛出 AssertionError,其 message 属性设置为等于 message 参数的值。
如果未定义 message 参数,则分配默认错误消息。
如果 message 参数是 Error 的实例,则将抛出错误而不是 AssertionError。
assert.deepStrictEqual(actual, expected[, message])#测试 actual 和 expected 参数之间的深度相等。
"深度"相等意味着子对象的可枚举"自有"属性也按照以下规则递归地评估。
Object.is() 比较原始值。[[Prototype]] 使用 === 运算符进行比较。Error 名称和消息总是被比较,即使它们不是可枚举的属性。Symbol 属性。Object 属性是无序比较的。Map 键和 Set 项是无序比较的。WeakMap 和 WeakSet 的比较不依赖于它们的值。
有关更多详细信息,请参见下文。import assert from 'assert/strict';
// 这失败了,因为 1 !== '1'。
assert.deepStrictEqual({ a: 1 }, { a: '1' });
// AssertionError: Expected inputs to be strictly deep-equal:
// + actual - expected
//
// {
// + a: 1
// - a: '1'
// }
// 以下对象没有自有的属性
const date = new Date();
const object = {};
const fakeDate = {};
Object.setPrototypeOf(fakeDate, Date.prototype);
// 不同的原型:
assert.deepStrictEqual(object, fakeDate);
// AssertionError: Expected inputs to be strictly deep-equal:
// + actual - expected
//
// + {}
// - Date {}
// 不同的类型标签:
assert.deepStrictEqual(date, fakeDate);
// AssertionError: Expected inputs to be strictly deep-equal:
// + actual - expected
//
// + 2018-04-26T00:49:08.604Z
// - Date {}
assert.deepStrictEqual(NaN, NaN);
// OK,因为 Object.is(NaN, NaN) 为 true。
// 不同的解封装数字:
assert.deepStrictEqual(new Number(1), new Number(2));
// AssertionError: Expected inputs to be strictly deep-equal:
// + actual - expected
//
// + [Number: 1]
// - [Number: 2]
assert.deepStrictEqual(new String('foo'), Object('foo'));
// OK,因为对象和字符串在解封装时是相同的。
assert.deepStrictEqual(-0, -0);
// OK
// 不同的零:
assert.deepStrictEqual(0, -0);
// AssertionError: Expected inputs to be strictly deep-equal:
// + actual - expected
//
// + 0
// - -0
const symbol1 = Symbol();
const symbol2 = Symbol();
assert.deepStrictEqual({ [symbol1]: 1 }, { [symbol1]: 1 });
// OK,因为它是两个对象上的相同符号。
assert.deepStrictEqual({ [symbol1]: 1 }, { [symbol2]: 1 });
// AssertionError [ERR_ASSERTION]: Inputs identical but not reference equal:
//
// {
// [Symbol()]: 1
// }
const weakMap1 = new WeakMap();
const weakMap2 = new WeakMap([[{}, {}]]);
const weakMap3 = new WeakMap();
weakMap3.unequal = true;
assert.deepStrictEqual(weakMap1, weakMap2);
// OK,因为无法比较条目
// 失败,因为 weakMap3 有一个 weakMap1 不包含的属性:
assert.deepStrictEqual(weakMap1, weakMap3);
// AssertionError: Expected inputs to be strictly deep-equal:
// + actual - expected
//
// WeakMap {
// + [items unknown]
// - [items unknown],
// - unequal: true
// }const assert = require('assert/strict');
// 这失败了,因为 1 !== '1'。
assert.deepStrictEqual({ a: 1 }, { a: '1' });
// AssertionError: Expected inputs to be strictly deep-equal:
// + actual - expected
//
// {
// + a: 1
// - a: '1'
// }
// 以下对象没有自有的属性
const date = new Date();
const object = {};
const fakeDate = {};
Object.setPrototypeOf(fakeDate, Date.prototype);
// 不同的原型:
assert.deepStrictEqual(object, fakeDate);
// AssertionError: Expected inputs to be strictly deep-equal:
// + actual - expected
//
// + {}
// - Date {}
// 不同的类型标签:
assert.deepStrictEqual(date, fakeDate);
// AssertionError: Expected inputs to be strictly deep-equal:
// + actual - expected
//
// + 2018-04-26T00:49:08.604Z
// - Date {}
assert.deepStrictEqual(NaN, NaN);
// OK,因为 Object.is(NaN, NaN) 为 true。
// 不同的解封装数字:
assert.deepStrictEqual(new Number(1), new Number(2));
// AssertionError: Expected inputs to be strictly deep-equal:
// + actual - expected
//
// + [Number: 1]
// - [Number: 2]
assert.deepStrictEqual(new String('foo'), Object('foo'));
// OK,因为对象和字符串在解封装时是相同的。
assert.deepStrictEqual(-0, -0);
// OK
// 不同的零:
assert.deepStrictEqual(0, -0);
// AssertionError: Expected inputs to be strictly deep-equal:
// + actual - expected
//
// + 0
// - -0
const symbol1 = Symbol();
const symbol2 = Symbol();
assert.deepStrictEqual({ [symbol1]: 1 }, { [symbol1]: 1 });
// OK,因为它是两个对象上的相同符号。
assert.deepStrictEqual({ [symbol1]: 1 }, { [symbol2]: 1 });
// AssertionError [ERR_ASSERTION]: Inputs identical but not reference equal:
//
// {
// [Symbol()]: 1
// }
const weakMap1 = new WeakMap();
const weakMap2 = new WeakMap([[{}, {}]]);
const weakMap3 = new WeakMap();
weakMap3.unequal = true;
assert.deepStrictEqual(weakMap1, weakMap2);
// OK,因为无法比较条目
// 失败,因为 weakMap3 有一个 weakMap1 不包含的属性:
assert.deepStrictEqual(weakMap1, weakMap3);
// AssertionError: Expected inputs to be strictly deep-equal:
// + actual - expected
//
// WeakMap {
// + [items unknown]
// - [items unknown],
// - unequal: true
// }
如果值不相等,则抛出 AssertionError,其 message 属性设置为等于 message 参数的值。
如果未定义 message 参数,则分配默认错误消息。
如果 message 参数是 Error 的实例,则将抛出错误而不是 AssertionError。
assert.doesNotMatch(string, regexp[, message])#期望 string 输入与正则表达式不匹配。
import assert from 'assert/strict';
assert.doesNotMatch('I will fail', /fail/);
// AssertionError [ERR_ASSERTION]: The input was expected to not match the ...
assert.doesNotMatch(123, /pass/);
// AssertionError [ERR_ASSERTION]: The "string" argument must be of type string.
assert.doesNotMatch('I will pass', /different/);
// OKconst assert = require('assert/strict');
assert.doesNotMatch('I will fail', /fail/);
// AssertionError [ERR_ASSERTION]: The input was expected to not match the ...
assert.doesNotMatch(123, /pass/);
// AssertionError [ERR_ASSERTION]: The "string" argument must be of type string.
assert.doesNotMatch('I will pass', /different/);
// OK
如果值匹配,或者 string 参数的类型不是 string,则抛出 AssertionError,其 message 属性设置为等于 message 参数的值。
如果未定义 message 参数,则分配默认错误消息。
如果 message 参数是 Error 的实例,则将抛出错误而不是 AssertionError。
assert.doesNotReject(asyncFn[, error][, message])#asyncFn <Function> | <Promise>error <RegExp> | <Function>message <string>等待 asyncFn promise,或者,如果 asyncFn 是函数,则立即调用该函数并等待返回的 promise 完成。
然后会检查 promise 是否没有被拒绝。
如果 asyncFn 是函数并且它同步抛出错误,则 assert.doesNotReject() 将返回使用使用该错误拒绝的 Promise。
如果函数没有返回 promise,则 assert.doesNotReject() 将返回使用 ERR_INVALID_RETURN_VALUE 错误拒绝的 Promise。
在这两种情况下,都会跳过错误句柄。
使用 assert.doesNotReject() 实际上没有用,因为捕获拒绝