Node.js v10.12.0 文档


assert - 断言#

查看英文版参与翻译

稳定性: 2 - 稳定的

assert 模块提供了断言测试的函数,用于测试不变式。

strictlegacy 两种模式,建议只使用 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 属性(messagename)以及:

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模式#

本段落暂不提供翻译

Stability: 0 - Deprecated: Use strict mode instead.

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

Stability: 0 - Deprecated: Use 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 参数是否深度相等。 深度相等意味着子对象中可枚举的自身属性也会按以下规则递归地比较。

比较的详细说明#

查看英文版参与翻译

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(asyncFn[, error][, message])#

查看英文版参与翻译

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.

Please note: Using assert.doesNotReject() is actually not useful because there is little benefit by 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().

(async () => {
  await assert.doesNotReject(
    async () => {
      throw new TypeError('Wrong value');
    },
    SyntaxError
  );
})();
assert.doesNotReject(Promise.reject(new TypeError('Wrong value')))
  .then(() => {
    // ...
  });

assert.doesNotThrow(fn[, error][, message])#

查看英文版参与翻译

Asserts that the function fn does not throw an error.

Please note: Using assert.doesNotThrow() is actually not useful because there is no benefit by 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:

assert.doesNotThrow(
  () => {
    throw new TypeError('Wrong value');
  },
  SyntaxError
);

However, the following will result in an AssertionError with the message 'Got unwanted exception...':

assert.doesNotThrow(
  () => {
    throw new TypeError('Wrong value');
  },
  TypeError
);

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:

assert.doesNotThrow(
  () => {
    throw new TypeError('Wrong value');
  },
  /Wrong value/,
  'Whoops'
);
// Throws: AssertionError: Got unwanted exception: Whoops

assert.equal(actual, expected[, message])#

本段落暂不提供翻译

Strict mode

An alias of assert.strictEqual().

Legacy mode

Stability: 0 - Deprecated: Use 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[, stackStartFn]]])#

查看英文版参与翻译

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

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 stackStartFn 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 不为 undefinednull,则抛出 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

Stability: 0 - Deprecated: Use 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

Stability: 0 - Deprecated: Use 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(asyncFn[, error][, message])#

查看英文版参与翻译

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.

(async () => {
  await assert.rejects(
    async () => {
      throw new TypeError('Wrong value');
    },
    {
      name: 'TypeError',
      message: 'Wrong value'
    }
  );
})();
assert.rejects(
  Promise.reject(new Error('Wrong value')),
  Error
).then(() => {
  // ...
});

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

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(fn[, error][, message])#

查看英文版参与翻译

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:

const err = new TypeError('Wrong value');
err.code = 404;
err.foo = 'bar';
err.info = {
  nested: true,
  baz: 'text'
};
err.reg = /abc/i;

assert.throws(
  () => {
    throw err;
  },
  {
    name: 'TypeError',
    message: 'Wrong value',
    info: {
      nested: true,
      baz: 'text'
    }
    // Note that only properties on the validation object will be tested for.
    // Using nested objects requires all properties to be present. Otherwise
    // the validation is going to fail.
  }
);

// Using regular expressions to validate error properties:
assert.throws(
  () => {
    throw err;
  },
  {
    // The `name` and `message` properties are strings and using regular
    // expressions on those will match against the string. If they fail, an
    // error is thrown.
    name: /^TypeError$/,
    message: /Wrong/,
    foo: 'bar',
    info: {
      nested: true,
      // It is not possible to use regular expressions for nested properties!
      baz: 'text'
    },
    // The `reg` property contains a regular expression and only if the
    // validation object contains an identical regular expression, it is going
    // to pass.
    reg: /abc/i
  }
);

// Fails due to the different `message` and `name` properties:
assert.throws(
  () => {
    const otherErr = new Error('Not found');
    otherErr.code = 404;
    throw otherErr;
  },
  err // This tests for `message`, `name` and `code`.
);

Validate instanceof using constructor:

assert.throws(
  () => {
    throw new Error('Wrong value');
  },
  Error
);

Validate error message using RegExp:

Using a regular expression runs .toString on the error object, and will therefore also include the error name.

assert.throws(
  () => {
    throw new Error('Wrong value');
  },
  /^Error: Wrong value$/
);

Custom error validation:

assert.throws(
  () => {
    throw new Error('Wrong value');
  },
  function(err) {
    if ((err instanceof Error) && /value/.test(err)) {
      return true;
    }
  },
  'unexpected error'
);

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

function throwingFirst() {
  throw new Error('First');
}
function throwingSecond() {
  throw new Error('Second');
}
function notThrowing() {}

// The second argument is a string and the input function threw an Error.
// The first case will not throw as it does not match for the error message
// thrown by the input function!
assert.throws(throwingFirst, 'Second');
// In the next example the message has no benefit over the message from the
// error and since it is not clear if the user intended to actually match
// against the error message, Node.js thrown an `ERR_AMBIGUOUS_ARGUMENT` error.
assert.throws(throwingSecond, 'Second');
// Throws an error:
// TypeError [ERR_AMBIGUOUS_ARGUMENT]

// The string is only used (as message) in case the function does not throw:
assert.throws(notThrowing, 'Second');
// AssertionError [ERR_ASSERTION]: Missing expected exception: Second

// If it was intended to match for the error message do this instead:
assert.throws(throwingSecond, /Second$/);
// Does not throw because the error messages match.
assert.throws(throwingFirst, /Second$/);
// Throws an error:
// Error: First
//     at throwingFirst (repl:2:9)

Due to the confusing notation, it is recommended not to use a string as the second argument. This might lead to difficult-to-spot errors.