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


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

🌐 Asserts that the function fn does not throw an error.

实际上使用 assert.doesNotThrow() 并没有什么用,因为捕获错误然后再抛出并没有任何好处。相反,可以考虑在不应抛出异常的特定代码路径旁边添加注释,并尽量保持错误信息的表达性。

🌐 Using assert.doesNotThrow() is actually not useful because there is no benefit in 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.

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

🌐 When assert.doesNotThrow() is called, it will immediately call the fn function.

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

🌐 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.

如果指定,error 可以是 ClassRegExp 或验证函数。更多详情请参见 assert.throws()

🌐 If specified, error can be a Class, RegExp, or a validation function. See assert.throws() for more details.

例如,下面的代码会抛出 TypeError,因为断言中没有匹配的错误类型:

🌐 The following, for instance, will throw the TypeError because there is no matching error type in the assertion:

import assert from 'node:assert/strict';

assert.doesNotThrow(
  () => {
    throw new TypeError('Wrong value');
  },
  SyntaxError
);const assert = require('node:assert/strict');

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

但是,以下操作将导致出现带有消息 'Got unwanted exception...' 的 AssertionError

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

import assert from 'node:assert/strict';

assert.doesNotThrow(
  () => {
    throw new TypeError('Wrong value');
  },
  TypeError
);const assert = require('node:assert/strict');

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

如果抛出 AssertionError 并为 message 参数提供了值,则该 message 的值将附加到 AssertionError 消息中:

🌐 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:

import assert from 'node:assert/strict';

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

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