- assert - 断言
- Buffer - 缓冲器
- child_process - 子进程
- cluster - 集群
- console - 控制台
- crypto - 加密
- dgram - 数据报
- dns - 域名服务器
- Error - 异常
- events - 事件
- fs - 文件系统
- global - 全局变量
- http - HTTP
- https - HTTPS
- module - 模块
- net - 网络
- os - 操作系统
- path - 路径
- process - 进程
- querystring - 查询字符串
- readline - 逐行读取
- repl - 交互式解释器
- stream - 流
- string_decoder - 字符串解码器
- timer - 定时器
- tls - 安全传输层
- tty - 终端
- url - 网址
- util - 实用工具
- v8 - V8引擎
- vm - 虚拟机
- zlib - 压缩
Node.js v10.8.0 文档
目录
- 
- strict模式
- legacy模式
- assert(value[, message])
- assert.deepEqual(actual, expected[, message])
- assert.doesNotReject(block[, error][, message])
- assert.doesNotThrow(block[, error][, message])
- assert.equal(actual, expected[, message])
- assert.fail([message])
- assert.fail(actual, expected[, message[, operator[, stackStartFunction]]])
- assert.ifError(value)
- 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(block[, error][, message])
- assert.strictEqual(actual, expected[, message])
- assert.throws(block[, error][, message])
 
assert - 断言#
assert 模块提供了断言测试的函数,用于测试不变式。
有 strict 与 legacy 两种模式,建议只使用 strict模式。
查看 MDN的等式比较指南,了解更多关于等式比较的信息。
assert.AssertionError 类#
Error 的一个子类,表明断言的失败。
assert 模块抛出的所有错误都是 AssertionError 类的实例。
new assert.AssertionError(options)#
- 
options<Object>- message<string> 如果有值,则错误信息会被设为该值。
- actual<any> 错误实例的- actual属性会被设为该值。用于- actual错误输入,例如使用- assert.strictEqual()。
- expected<any> 错误实例的- expected属性会被设为该值。用于- expected错误输入,例如使用- assert.strictEqual()。
- operator<string> 错误实例的- operator属性会被设为该值。用于表明比较时使用的是哪个操作(或触发错误的是哪个断言函数)。
- stackStartFn<Function> 如果有值,则由提供的函数生成堆栈踪迹。
 
Error 的一个子类,表明断言的失败。
所有实例都包含内置的 Error 属性(message 和 name)以及:
- actual<any> 被设为实际值,例如使用- assert.strictEqual()。
- expected<any> 被设为期望值,例如使用- assert.strictEqual()。
- generatedMessage<boolean> 表明信息是否为自动生成的。
- code<string> 总是被设为- ERR_ASSERTION,表明错误是一个断言错误。
- operator<string> 被设为传入的运算符的值。
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 [ERR_ASSERTION]');
  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);
}
strict模式#
当使用 strict 模式时,任何 assert 函数都会使用严格函数模式的等式。
所以 assert.deepEqual() 会等同于 assert.deepStrictEqual()。
除此以外,涉及对象的错误信息会产生一个错误差异比较,而不是展示双方的对象。
legacy 模式则不会这样。
可以通过以下方式使用:
const assert = require('assert').strict;
错误差异比较的例子:
const assert = require('assert').strict;
assert.deepEqual([[[1, 2, 3]], 4, 5], [[[1, 2, '3']], 4, 5]);
// AssertionError: Input A expected to strictly deep-equal input B:
// + expected - actual ... Lines skipped
//
//   [
//     [
// ...
//       2,
// -     3
// +     '3'
//     ],
// ...
//     5
//   ]
使用 NODE_DISABLE_COLORS 环境变量可以禁用颜色。
注意,这也会禁用 REPL 中的其他颜色。
legacy模式#
本段落不提供翻译
When accessing assert directly instead of using the strict property, the
Abstract Equality Comparison will be used for any function without "strict"
in its name, such as assert.deepEqual().
It can be accessed using:
const assert = require('assert');
It is recommended to use the strict mode instead as the
Abstract Equality Comparison can often have surprising results. This is
especially true for assert.deepEqual(), where the comparison rules are
lax:
// WARNING: This does not throw an AssertionError!
assert.deepEqual(/a/gi, new Date());
assert(value[, message])#
assert.ok() 的别名。
assert.deepEqual(actual, expected[, message])#
本段落不提供翻译
Strict mode
An alias of assert.deepStrictEqual().
Legacy mode
assert.deepStrictEqual() instead.Tests for deep equality between the actual and expected parameters.
Primitive values are compared with the Abstract Equality Comparison
( == ).
Only enumerable "own" properties are considered. The
assert.deepEqual() implementation does not test the
[[Prototype]] of objects or enumerable own Symbol
properties. For such checks, consider using assert.deepStrictEqual()
instead. assert.deepEqual() can have potentially surprising results. The
following example does not throw an AssertionError because the properties on
the RegExp object are not enumerable:
// WARNING: This does not throw an AssertionError!
assert.deepEqual(/a/gi, new Date());
An exception is made for Map and Set. Maps and Sets have their
contained items compared too, as expected.
"Deep" equality means that the enumerable "own" properties of child objects are evaluated also:
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
// Values of b are different:
assert.deepEqual(obj1, obj2);
// AssertionError: { a: { b: 1 } } deepEqual { a: { b: 2 } }
assert.deepEqual(obj1, obj3);
// OK
// Prototypes are ignored:
assert.deepEqual(obj1, obj4);
// AssertionError: { a: { b: 1 } } deepEqual {}
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.
assert.deepStrictEqual(actual, expected[, message])#
测试 actual 参数与 expected 参数是否深度相等。
深度相等意味着子对象中可枚举的自身属性也会按以下规则递归地比较。
比较的详细说明#
- 原始值运用 SameValue比较法进行比较,使用 Object.is()函数。
- 对象的类型标签应该相同。
- 对象的原型使用全等运算符比较。
- 只比较可枚举的自身属性。
- Error的名称与信息也会比较,即使不是可枚举的属性。
- 可枚举的自身 Symbol属性也会比较。
- 对象封装器 会同时比较对象与解封装后的值。
- Object属性的比较是无序的。
- Map键名与- Set子项的比较是无序的。
- 当两边的值不相同或遇到循环引用时,递归会停止。
- WeakMap与- WeakSet的比较不依赖于它们的值。
const assert = require('assert').strict;
// 失败,因为 1 !== '1'。
assert.deepStrictEqual({ a: 1 }, { a: '1' });
// AssertionError: Input A expected to strictly deep-equal input B:
// + expected - actual
//   {
// -   a: 1
// +   a: '1'
//   }
// 以下对象没有自身属性。
const date = new Date();
const object = {};
const fakeDate = {};
Object.setPrototypeOf(fakeDate, Date.prototype);
// 原型不同:
assert.deepStrictEqual(object, fakeDate);
// AssertionError: Input A expected to strictly deep-equal input B:
// + expected - actual
// - {}
// + Date {}
// 类型标签不同:
assert.deepStrictEqual(date, fakeDate);
// AssertionError: Input A expected to strictly deep-equal input B:
// + expected - actual
// - 2018-04-26T00:49:08.604Z
// + Date {}
assert.deepStrictEqual(NaN, NaN);
// 通过,因为使用的是 SameValue 比较法。
// 解封装后的数值不同:
assert.deepStrictEqual(new Number(1), new Number(2));
// AssertionError: Input A expected to strictly deep-equal input B:
// + expected - actual
// - [Number: 1]
// + [Number: 2]
assert.deepStrictEqual(new String('foo'), Object('foo'));
// 通过,因为对象与解封装后的字符串都完全相同。
assert.deepStrictEqual(-0, -0);
// 通过。
// SameValue 比较法中 0 与 -0 不同:
assert.deepStrictEqual(0, -0);
// AssertionError: Input A expected to strictly deep-equal input B:
// + expected - actual
// - 0
// + -0
const symbol1 = Symbol();
const symbol2 = Symbol();
assert.deepStrictEqual({ [symbol1]: 1 }, { [symbol1]: 1 });
// 通过,因为两边对象的 symbol 相同。
assert.deepStrictEqual({ [symbol1]: 1 }, { [symbol2]: 1 });
// AssertionError [ERR_ASSERTION]: Input objects not identical:
// {
//   [Symbol()]: 1
// }
const weakMap1 = new WeakMap();
const weakMap2 = new WeakMap([[{}, {}]]);
const weakMap3 = new WeakMap();
weakMap3.unequal = true;
assert.deepStrictEqual(weakMap1, weakMap2);
// 通过。
// 失败,因为 weakMap3 有一个 weakMap1 没有的属性:
assert.deepStrictEqual(weakMap1, weakMap3);
// AssertionError: Input A expected to strictly deep-equal input B:
// + expected - actual
//   WeakMap {
// -   [items unknown]
// +   [items unknown],
// +   unequal: true
//   }
如果两个值不相等,则抛出一个带有 message 属性的 AssertionError,其中 message 属性的值等于传入的 message 参数的值。
如果 message 参数为 undefined,则赋予默认的错误信息。
如果 message 参数是 Error 的实例,则会抛出它而不是 AssertionError。
assert.doesNotReject(block[, error][, message])#
- block<Function> | <Promise>
- error<RegExp> | <Function>
- message<string> | <Error>
等待 block 的 promise 完成,如果 block 是一个函数,则立即调用该函数并等待返回的 promise 完成,然后检查 promise 是否被 reject。
如果 block 是一个函数且同步地抛出一个错误,则 assert.doesNotReject() 会返回一个被 reject 的 Promise 并传入该错误。
如果该函数没有返回一个 promise,则 assert.doesNotReject() 会返回一个被 reject 的 Promise 并传入 ERR_INVALID_RETURN_VALUE 错误。
以上两种情况都会跳过错误处理函数。
error 可以是 Class、RegExp 或校验函数。
详见 assert.throws()。
该函数相当于 assert.doesNotThrow(),除了需要等待完成的异步特性。
(async () => {
  await assert.doesNotReject(
    async () => {
      throw new TypeError('错误信息');
    },
    SyntaxError
  );
})();
assert.doesNotReject(Promise.reject(new TypeError('错误信息')))
  .then(() => {
    // ...
  });
assert.doesNotThrow(block[, error][, message])#
- block<Function>
- error<RegExp> | <Function>
- message<string> | <Error>
断言 block 函数不会抛出错误。
当 assert.doesNotThrow() 被调用时,它会立即调用 block 函数。
如果抛出错误且错误类型与 error 参数指定的相同,则抛出 AssertionError。
如果错误类型不相同,或 error 参数为 undefined,则抛出错误。
error 可以是 Class、RegExp 或校验函数。
详见 assert.throws()。
以下例子会抛出 TypeError,因为在断言中没有匹配的错误类型:
assert.doesNotThrow(
  () => {
    throw new TypeError('错误信息');
  },
  SyntaxError
);
以下例子会抛出一个带有 Got unwanted exception (TypeError).. 信息的 AssertionError:
assert.doesNotThrow(
  () => {
    throw new TypeError('错误信息');
  },
  TypeError
);
如果抛出了 AssertionError 且有给 message 参数传值,则 message 参数的值会被附加到 AssertionError 的信息中:
assert.doesNotThrow(
  () => {
    throw new TypeError('错误信息');
  },
  /错误信息/,
  '出错啦'
);
// 抛出 AssertionError: Got unwanted exception: 出错啦
assert.equal(actual, expected[, message])#
本段落不提供翻译
Strict mode
An alias of assert.strictEqual().
Legacy mode
assert.strictEqual() instead.Tests shallow, coercive equality between the actual and expected parameters
using the Abstract Equality Comparison ( == ).
const assert = require('assert');
assert.equal(1, 1);
// OK, 1 == 1
assert.equal(1, '1');
// OK, 1 == '1'
assert.equal(1, 2);
// AssertionError: 1 == 2
assert.equal({ a: { b: 1 } }, { a: { b: 1 } });
// AssertionError: { a: { b: 1 } } == { a: { b: 1 } }
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.
assert.fail([message])#
抛出 AssertionError,并带上提供的错误信息或默认的错误信息。
如果 message 参数是 Error 的实例,则会抛出它而不是 AssertionError。
const assert = require('assert').strict;
assert.fail();
// 抛出 AssertionError [ERR_ASSERTION]: Failed
assert.fail('失败');
// 抛出 AssertionError [ERR_ASSERTION]: 失败
assert.fail(new TypeError('失败'));
// 抛出 TypeError: 失败
使用 assert.fail() 并带上多个参数的方法已被废弃。
assert.fail(actual, expected[, message[, operator[, stackStartFunction]]])#
本段落不提供翻译
- actual<any>
- expected<any>
- message<string> | <Error>
- operator<string> Default:- '!='
- stackStartFunction<Function> Default:- assert.fail
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
stackStartFunction 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.
const assert = require('assert').strict;
assert.fail('a', 'b');
// AssertionError [ERR_ASSERTION]: 'a' != 'b'
assert.fail(1, 2, undefined, '>');
// AssertionError [ERR_ASSERTION]: 1 > 2
assert.fail(1, 2, 'fail');
// AssertionError [ERR_ASSERTION]: fail
assert.fail(1, 2, 'whoops', '>');
// AssertionError [ERR_ASSERTION]: whoops
assert.fail(1, 2, new TypeError('need array'));
// TypeError: need array
In the last three cases actual, expected, and operator have no
influence on the error message.
Example use of stackStartFunction for truncating the exception's stacktrace:
function suppressFrame() {
  assert.fail('a', 'b', undefined, '!==', suppressFrame);
}
suppressFrame();
// AssertionError [ERR_ASSERTION]: 'a' !== 'b'
//     at repl:1:1
//     at ContextifyScript.Script.runInThisContext (vm.js:44:33)
//     ...
assert.ifError(value)#
- value<any>
如果 value 不为 undefined 或 null,则抛出 value。
可用于测试回调函数的 error 参数。
堆栈踪迹会包含传入 ifError() 的错误的所有帧,包括潜在的 ifError() 自身新增的帧。
例子:
const assert = require('assert').strict;
assert.ifError(null);
// 通过。
assert.ifError(0);
// 抛出 AssertionError [ERR_ASSERTION]: ifError got unwanted exception: 0
assert.ifError('错误信息');
// 抛出 AssertionError [ERR_ASSERTION]: ifError got unwanted exception: '错误信息'
assert.ifError(new Error());
// 抛出 AssertionError [ERR_ASSERTION]: ifError got unwanted exception: Error
// 添加一些错误帧。
let err;
(function errorFrame() {
  err = new Error('错误信息');
})();
(function ifErrorFrame() {
  assert.ifError(err);
})();
// AssertionError [ERR_ASSERTION]: ifError got unwanted exception: 错误信息
//     at ifErrorFrame
//     at errorFrame
assert.notDeepEqual(actual, expected[, message])#
本段落不提供翻译
Strict mode
An alias of assert.notDeepStrictEqual().
Legacy mode
assert.notDeepStrictEqual() instead.Tests for any deep inequality. Opposite of assert.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.notDeepEqual(obj1, obj1);
// AssertionError: { a: { b: 1 } } notDeepEqual { a: { b: 1 } }
assert.notDeepEqual(obj1, obj2);
// OK
assert.notDeepEqual(obj1, obj3);
// AssertionError: { a: { b: 1 } } notDeepEqual { a: { b: 1 } }
assert.notDeepEqual(obj1, obj4);
// OK
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.
assert.notDeepStrictEqual(actual, expected[, message])#
测试 actual 参数与 expected 参数是否不深度全等。
与 assert.deepStrictEqual() 相反。
const assert = require('assert').strict;
assert.notDeepStrictEqual({ a: 1 }, { a: '1' });
// 测试通过。
如果两个值深度全等,则抛出一个带有 message 属性的 AssertionError,其中 message 属性的值等于传入的 message 参数的值。
如果 message 参数为 undefined,则赋予默认的错误信息。
如果 message 参数是 Error 的实例,则会抛出它而不是 AssertionError。
assert.notEqual(actual, expected[, message])#
本段落不提供翻译
Strict mode
An alias of assert.notStrictEqual().
Legacy mode
assert.notStrictEqual() instead.Tests shallow, coercive inequality with the Abstract Equality Comparison
( != ).
const assert = require('assert');
assert.notEqual(1, 2);
// OK
assert.notEqual(1, 1);
// AssertionError: 1 != 1
assert.notEqual(1, '1');
// AssertionError: 1 != '1'
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.
assert.notStrictEqual(actual, expected[, message])#
使用 SameValue比较法测试 actual 参数与 expected 参数是否不全等。
const assert = require('assert').strict;
assert.notStrictEqual(1, 2);
// 测试通过。
assert.notStrictEqual(1, 1);
// 抛出 AssertionError [ERR_ASSERTION]: Identical input passed to notStrictEqual: 1
assert.notStrictEqual(1, '1');
// 测试通过。
如果两个值全等,则抛出一个带有 message 属性的 AssertionError,其中 message 属性的值等于传入的 message 参数的值。
如果 message 参数为 undefined,则赋予默认的错误信息。
如果 message 参数是 Error 的实例,则会抛出它而不是 AssertionError。
assert.ok(value[, message])#
测试 value 是否为真值。
相当于 assert.equal(!!value, true, message)。
如果 value 不为真值,则抛出一个带有 message 属性的 AssertionError,其中 message 属性的值等于传入的 message 参数的值。
如果 message 参数为 undefined,则赋予默认的错误信息。
如果 message 参数是 Error 的实例,则会抛出它而不是 AssertionError。
如果没有传入参数,则 message 会被设为字符串 'No value argument passed to `assert.ok()`'。
const assert = require('assert').strict;
assert.ok(true);
// 测试通过。
assert.ok(1);
// 测试通过。
assert.ok();
// 抛出 AssertionError: No value argument passed to `assert.ok()`
assert.ok(false, '不是真值');
// 抛出 AssertionError: 不是真值
// 在 repl 中:
assert.ok(typeof 123 === 'string');
// 抛出 AssertionError: false == true
// 在文件中(例如 test.js):
assert.ok(typeof 123 === 'string');
// 抛出 AssertionError: The expression evaluated to a falsy value:
//
//   assert.ok(typeof 123 === 'string')
assert.ok(false);
// 抛出 AssertionError: The expression evaluated to a falsy value:
//
//   assert.ok(false)
assert.ok(0);
// 抛出 AssertionError: The expression evaluated to a falsy value:
//
//   assert.ok(0)
// 等同于 `assert()`:
assert(0);
// 抛出 AssertionError: The expression evaluated to a falsy value:
//
//   assert(0)
assert.rejects(block[, error][, message])#
- block<Function> | <Promise>
- error<RegExp> | <Function> | <Object> | <Error>
- message<string> | <Error>
等待 block 的 promise 完成,如果 block 是一个函数,则立即调用该函数并等待返回的 promise 完成,然后检查 promise 是否被 reject。
如果 block 是一个函数且同步地抛出一个错误,则 assert.rejects() 会返回一个被 reject 的 Promise 并传入该错误。
如果该函数没有返回一个 promise,则 assert.rejects() 会返回一个被 reject 的 Promise 并传入 ERR_INVALID_RETURN_VALUE 错误。
以上两种情况都会跳过错误处理函数。
该函数相当于 assert.throws(),除了需要等待完成的异步特性。
error 可以是 Class、RegExp、校验函数、每个属性都会被测试的对象、或每个属性(包括不可枚举的 message 和 name 属性)都会被测试的错误实例。
如果指定了 message,则当 block 没被 reject 时,message 参数会作为 AssertionError 的错误信息。
(async () => {
  await assert.rejects(
    async () => {
      throw new TypeError('错误信息');
    },
    {
      name: 'TypeError',
      message: '错误信息'
    }
  );
})();
assert.rejects(
  Promise.reject(new Error('错误信息')),
  Error
).then(() => {
  // ...
});
注意,error 不能是字符串。
如果第二个参数是字符串,则视为不传入 error,且字符串会用于 message。
这可能会造成误解。
如果需要使用字符串作为第二个参数,请仔细阅读 assert.throws() 中的例子。
assert.strictEqual(actual, expected[, message])#
使用 SameValue比较法测试 actual 参数与 expected 参数是否全等。
const assert = require('assert').strict;
assert.strictEqual(1, 2);
// 抛出 AssertionError [ERR_ASSERTION]: Input A expected to strictly equal input B:
// + expected - actual
// - 1
// + 2
assert.strictEqual(1, 1);
// 测试通过。
assert.strictEqual(1, '1');
// 抛出 AssertionError [ERR_ASSERTION]: Input A expected to strictly equal input B:
// + expected - actual
// - 1
// + '1'
如果两个值不全等,则抛出一个带有 message 属性的 AssertionError,其中 message 属性的值等于传入的 message 参数的值。
如果 message 参数为 undefined,则赋予默认的错误信息。
如果 message 参数是 Error 的实例,则会抛出它而不是 AssertionError。
assert.throws(block[, error][, message])#
- block<Function>
- error<RegExp> | <Function> | <Object> | <Error>
- message<string> | <Error>
断言 block 函数会抛出错误。
error 可以是 Class、RegExp、校验函数、每个属性都会被测试是否深度全等的校验对象、或每个属性(包括不可枚举的 message 和 name 属性)都会被测试是否深度全等的错误实例。
当使用对象时,可以使用正则表达式来校验字符串属性。
详见下面的例子。
如果指定了 message 参数,则当 block 函数不抛出错误时,message 参数会作为 AssertionError 的错误信息。
例子,error 参数为自定义的校验对象或错误实例:
const err = new TypeError('错误信息');
err.code = 404;
err.foo = 'bar';
err.info = {
  nested: true,
  baz: 'text'
};
err.reg = /abc/i;
assert.throws(
  () => {
    throw err;
  },
  {
    name: 'TypeError',
    message: '错误信息'
    info: {
      nested: true,
      baz: 'text'
    }
    // 注意,只有校验对象的属性会被测试。
    // 使用嵌套的对象必须提供全部属性,否则校验会失败。 
  }
);
// 使用正则表达式来校验错误属性:
assert.throws(
  () => {
    throw err;
  },
  {
    // `name` 和 `message` 属性为字符串,对它们使用正则表达式进行匹配。
    // 如果校验失败,则抛出错误。
    name: /^TypeError$/,
    message: /错误信息/,
    foo: 'bar',
    info: {
      nested: true,
      // 嵌套的属性不可以使用正则表达式!
      baz: 'text'
    },
    // `reg` 属性包含了一个正则表达式,只有校验对象也包含一个完全相同的正则表达式时,校验才会通过。
    reg: /abc/i
  }
);
// 失败,因为 `message` 属性与 `name` 属性不同:
assert.throws(
  () => {
    const otherErr = new Error('未找到');
    otherErr.code = 404;
    throw otherErr;
  },
  err // 会测试 `message`、`name` 和 `code`。
);
例子,error 参数为构造函数:
assert.throws(
  () => {
    throw new Error('错误信息');
  },
  Error
);
例子,error 参数为 RegExp:
使用正则表达式运行错误对象的 .toString, 且包括错误的名称。
assert.throws(
  () => {
    throw new Error('错误信息');
  },
  /^Error: 错误信息$/
);
例子,error 参数为自定义函数:
assert.throws(
  () => {
    throw new Error('错误信息');
  },
  function(err) {
    if ((err instanceof Error) && /错误/.test(err)) {
      return true;
    }
  },
  '不是期望的错误'
);
注意,error 不能是字符串。
如果第二个参数是字符串,则视为不传入 error,且字符串会用于 message。
这可能会造成误解。
使用与抛出的错误信息相同的信息,会导致 ERR_AMBIGUOUS_ARGUMENT 错误。
如果需要使用字符串作为第二个参数,请仔细阅读下面的例子。
function throwingFirst() {
  throw new Error('错误一');
}
function throwingSecond() {
  throw new Error('错误二');
}
function notThrowing() {}
// 第二个参数为字符串,且输入函数抛出了错误。
// 第一个例子不会抛出错误,因为它没有匹配到输入函数抛出的错误信息!
assert.throws(throwingFirst, '错误二');
// 第二个例子中,传入的信息接近错误信息,
// 且没有表述清楚用户是否有意匹配错误信息,
// 所以 Node.js 会抛出 `ERR_AMBIGUOUS_ARGUMENT` 错误。
assert.throws(throwingSecond, '错误二');
// 抛出错误:
// TypeError [ERR_AMBIGUOUS_ARGUMENT]
// 当函数没有抛出错误时,字符串可用于错误信息:
assert.throws(notThrowing, '错误二');
// 抛出 AssertionError [ERR_ASSERTION]: Missing expected exception: 错误二
// 如果想要匹配到错误信息,可以如下:
assert.throws(throwingSecond, /错误二$/);
// 没有抛出错误,因为错误信息匹配。
assert.throws(throwingFirst, /错误二$/);
// 抛出错误:
// Error: 错误一
//     at throwingFirst (repl:2:9)
鉴于会混淆语句,建议不要使用字符串作为第二个参数。 这可能会导致不易定位的错误。