Node.js v12.4.0 文档


assert(断言)#

中英对照提交修改

稳定性: 2 - 稳定

assert 模块提供了一组简单的断言测试,可用于测试不变量。

存在严格模式(strict)和遗留模式(legacy),但建议仅使用严格模式

有关使用的相等性比较的更多信息,参阅 MDN 的指南 - 相等性比较和相同性

assert.AssertionError 类#

中英对照提交修改

Error 的子类,表明断言的失败。 assert 模块抛出的所有错误都是 AssertionError 类的实例。

new assert.AssertionError(options)#

查看v10.x中文文档

  • options <Object>

    • message <string> If provided, the error message is going to be set to this value.
    • actual <any> The actual property on the error instance is going to contain this value. Internally used for the actual error input in case e.g., assert.strictEqual() is used.
    • expected <any> The expected property on the error instance is going to contain this value. Internally used for the expected error input in case e.g., assert.strictEqual() is used.
    • operator <string> The operator property on the error instance is going to contain this value. Internally used to indicate what operation was used for comparison (or what assertion function triggered the error).
    • stackStartFn <Function> If provided, the generated stack trace is going to remove all frames up to the provided function.

A subclass of Error that indicates the failure of an assertion.

All instances contain the built-in Error properties (message and name) and:

  • actual <any> Set to the actual value in case e.g., assert.strictEqual() is used.
  • expected <any> Set to the expected value in case e.g., assert.strictEqual() is used.
  • generatedMessage <boolean> Indicates if the message was auto-generated (true) or not.
  • code <string> This is always set to the string ERR_ASSERTION to indicate that the error is actually an assertion error.
  • operator <string> Set to the passed in operator value.
const assert = require('assert');

// Generate an AssertionError to compare the error message later:
const { message } = new assert.AssertionError({
  actual: 1,
  expected: 2,
  operator: 'strictEqual'
});

// Verify error output:
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);
}

严格模式#

查看v10.x中文文档

When using the strict mode, any assert function will use the equality used in the strict function mode. So assert.deepEqual() will, for example, work the same as assert.deepStrictEqual().

On top of that, error messages which involve objects produce an error diff instead of displaying both objects. That is not the case for the legacy mode.

It can be accessed using:

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 NODE_DISABLE_COLORS environment variable. Please note that this will also deactivate the colors in the REPL.

遗留模式#

中英对照提交修改

稳定性: 0 - 废弃: 改为使用严格模式。

当直接访问 assert 而不是使用 strict 属性时,将对名称中没有 "strict" 的任何函数(例如 assert.deepEqual())使用抽象的相等性比较

它可以使用以下方式访问:

const assert = require('assert');

建议使用严格模式,因为抽象的相等性比较通常会产生意外的结果。 特别是对于 assert.deepEqual(),其中的比较规则是松散的:

// 注意:这不会抛出 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

稳定性: 0 - 废弃: 改为使用 assert.deepStrictEqual()

Tests for deep equality between the actual and expected parameters. Consider using assert.deepStrictEqual() instead. assert.deepEqual() can have potentially surprising results.

"Deep" equality means that the enumerable "own" properties of child objects are also recursively evaluated by the following rules.

比较运算的详细说明#

查看v10.x中文文档

  • Primitive values are compared with the Abstract Equality Comparison ( == ).
  • Type tags of objects should be the same.
  • Only enumerable "own" properties are considered.
  • Error names and messages are always compared, even if these are not enumerable properties.
  • Object wrappers are compared both as objects and unwrapped values.
  • Object properties are compared unordered.
  • Map keys and Set items are compared unordered.
  • Recursion stops when both sides differ or both sides encounter a circular reference.
  • Implementation does not test the [[Prototype]] of objects.
  • Symbol properties are not compared.
  • WeakMap and WeakSet comparison does not rely on their values.

The following example does not throw an AssertionError because the primitives are considered equal by the Abstract Equality Comparison ( == ).

// WARNING: This does not throw an AssertionError!
assert.deepEqual('+00000000', false);

"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 参数之间的深度相等。 深度相等意味着子对象的可枚举的自身属性也通过以下规则进行递归计算。

Comparison details#

暂无中英对照

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

// This fails because 1 !== '1'.
assert.deepStrictEqual({ a: 1 }, { a: '1' });
// AssertionError: Expected inputs to be strictly deep-equal:
// + actual - expected
//
//   {
// +   a: 1
// -   a: '1'
//   }

// The following objects don't have own properties
const date = new Date();
const object = {};
const fakeDate = {};
Object.setPrototypeOf(fakeDate, Date.prototype);

// Different [[Prototype]]:
assert.deepStrictEqual(object, fakeDate);
// AssertionError: Expected inputs to be strictly deep-equal:
// + actual - expected
//
// + {}
// - Date {}

// Different type tags:
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, because of the SameValue comparison

// Different unwrapped numbers:
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 because the object and the string are identical when unwrapped.

assert.deepStrictEqual(-0, -0);
// OK

// Different zeros using the SameValue Comparison:
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, because it is the same symbol on both objects.

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, because it is impossible to compare the entries

// Fails because weakMap3 has a property that weakMap1 does not contain:
assert.deepStrictEqual(weakMap1, weakMap3);
// AssertionError: Expected inputs to be strictly deep-equal:
// + actual - expected
//
//   WeakMap {
// +   [items unknown]
// -   [items unknown],
// -   unequal: true
//   }

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

查看v10.x中文文档

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.

Using assert.doesNotReject() is actually not useful because there is little benefit in 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])#

中英对照提交修改

断言 fn 函数不会抛出错误。

使用 assert.doesNotThrow() 实际上没有用处,因为捕获错误然后重新抛出它没有任何好处。 应该考虑在不应抛出错误的特定代码路径旁边添加注释,并尽可能保留错误消息。

当调用 assert.doesNotThrow() 时,它将立即调用 fn 函数。

如果抛出错误并且它与 error 参数指定的类型相同,则抛出 AssertionError。 如果错误的类型不同,或者 error 参数未定义,则错误将传播回调用方。

如果指定,则 error 可以是 ClassRegExp 或验证函数。 有关更多详细信息,请参见 assert.throws()

例如,以下示例将抛出 TypeError,因为断言中没有匹配的错误类型:

assert.doesNotThrow(
  () => {
    throw new TypeError('错误值');
  },
  SyntaxError
);

以下示例将导致 AssertionError,并显示消息 'Got unwanted exception...':

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

稳定性: 0 - 废弃: 改为使用 assert.strictEqual()

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]]])#

暂无中英对照

稳定性: 0 - 废弃: 改为使用 assert.fail([message]) 或 other assert functions 。

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

稳定性: 0 - 废弃: 改为使用 assert.notDeepStrictEqual()

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])#

中英对照提交修改

测试深度严格的不平等。 与 assert.deepStrictEqual() 相反。

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

assert.notDeepStrictEqual({ a: 1 }, { a: '1' });
// 通过。

如果值深度且严格相等,则抛出 AssertionError,并将 message 属性设置为等于 message 参数的值。 如果未定义 message 参数,则会分配默认错误消息。 如果 message 参数是 Error 的实例,则它将被抛出而不是 AssertionError

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

暂无中英对照

Strict mode

An alias of assert.notStrictEqual().

Legacy mode

稳定性: 0 - 废弃: 改为使用 assert.notStrictEqual()

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])#

查看v10.x中文文档

Tests strict inequality between the actual and expected parameters as determined by the SameValue Comparison.

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

assert.notStrictEqual(1, 2);
// OK

assert.notStrictEqual(1, 1);
// AssertionError [ERR_ASSERTION]: Expected "actual" to be strictly unequal to:
//
// 1

assert.notStrictEqual(1, '1');
// OK

If the values are strictly 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.ok(value[, message])#

中英对照提交修改

测试 value 是否为真值。 等同于 assert.equal(!!value, true, message)

如果 value 不是真值,则抛出 AssertionError,并将 message 属性设置为等于 message 参数的值。 如果未定义 message 参数,则会分配默认错误消息。 如果 message 参数是 Error 的实例,则它将被抛出而不是 AssertionError。 如果没有传入任何参数,则将 message 设置为字符串:'No value argument passed to `assert.ok()`'

注意,在 repl 中,错误消息将与文件中抛出的错误消息不同!请参阅下文了解更多详情。

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

assert.ok(true);
// OK
assert.ok(1);
// OK

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])#

中英对照提交修改

等待 asyncFn Promise,或者,如果 asyncFn 是一个函数,则立即调用该函数并等待返回的 Promise 完成。 然后它将检查 Promise 是否被拒绝。

如果 asyncFn 是一个函数并且它同步抛出一个错误,则 assert.rejects() 将返回一个带有该错误的被拒绝的 Promise。 如果函数未返回 Promise,则 assert.rejects() 将返回一个被拒绝的 Promise,其中包含 ERR_INVALID_RETURN_VALUE 错误。 在这两种情况下都会跳过错误处理函数。

除了等待的异步性质之外,完成行为与 assert.throws() 完全相同。

如果指定,则 error 可以是 ClassRegExp、验证函数、将测试每个属性的对象、或者将测试每个属性的错误实例(包括不可枚举的 messagename 属性)。

如果指定 message,则当 asyncFn 无法拒绝时 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])#

查看v10.x中文文档

Tests strict equality between the actual and expected parameters as determined by the SameValue Comparison.

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

assert.strictEqual(1, 2);
// AssertionError [ERR_ASSERTION]: Expected inputs to be strictly equal:
//
// 1 !== 2

assert.strictEqual(1, 1);
// OK

assert.strictEqual('Hello foobar', 'Hello World!');
// AssertionError [ERR_ASSERTION]: Expected inputs to be strictly equal:
// + actual - expected
//
// + 'Hello foobar'
// - 'Hello World!'
//          ^

If the values are not strictly 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.throws(fn[, error][, message])#

查看v10.x中文文档

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 throws an `ERR_AMBIGUOUS_ARGUMENT` error.
assert.throws(throwingSecond, 'Second');
// 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:
// It does not throw because the error messages match.
assert.throws(throwingSecond, /Second$/);

// If the error message does not match, the error from within the function is
// not caught.
assert.throws(throwingFirst, /Second$/);
// 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.