Node.js v12.9.0 文档


assert(断言)#

查看v10.x中文文档

Stability: 2 - Stable

The assert module provides a set of assertion functions for verifying invariants. The module provides a recommended strict mode and a more lenient legacy mode.

assert.AssertionError 类#

中英对照提交修改

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

new assert.AssertionError(options)#

查看v10.x中文文档

  • options <Object>

    • message <string> If provided, the error message is set to this value.
    • actual <any> The actual property on the error instance.
    • expected <any> The expected property on the error instance.
    • operator <string> The operator property on the error instance.
    • stackStartFn <Function> If provided, the generated stack trace omits frames before this 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 argument for methods such as assert.strictEqual().
  • expected <any> Set to the expected value for methods such as assert.strictEqual().
  • generatedMessage <boolean> Indicates if the message was auto-generated (true) or not.
  • code <string> Value is always ERR_ASSERTION to show that the error is 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中文文档

In strict mode, assert functions use the comparison in the corresponding strict functions. For example, assert.deepEqual() will behave like assert.deepStrictEqual().

In strict mode, error messages for objects display a diff. In legacy mode, error messages for objects display the objects, often truncated.

To use strict 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 NODE_DISABLE_COLORS environment variable. This will also deactivate the colors in the REPL.

遗留模式#

查看v10.x中文文档

Legacy mode uses the Abstract Equality Comparison in:

To use legacy mode:

const assert = require('assert');

Whenever possible, use the strict mode instead. Otherwise, the Abstract Equality Comparison may cause 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

稳定性: 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])#

查看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 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(() => {
  // ...
});

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

查看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!'
//          ^

const apples = 1;
const oranges = 2;
assert.strictEqual(apples, oranges, `apples ${apples} !== oranges ${oranges}`);
// AssertionError [ERR_ASSERTION]: apples 1 !== oranges 2

assert.strictEqual(1, '1', new TypeError('Inputs are not identical'));
// TypeError: Inputs are not identical

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'
    }
    // 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');
  },
  (err) => {
    assert(err instanceof Error);
    assert(/value/.test(err));
    // Returning anything from validation functions besides `true` is not
    // recommended. Doing so results in the caught error being thrown again.
    // That is usually not the desired outcome. Throw an error about the
    // specific validation that failed instead (as done in this example).
    return true;
  },
  'unexpected error'
);

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.