assert.doesNotReject(asyncFn[, error][, message])


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

【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.】

如果 asyncFn 是一个函数并且同步抛出错误,assert.doesNotReject() 将返回一个带有该错误的被拒绝的 Promise。如果函数不返回 Promise,assert.doesNotReject() 将返回一个带有 ERR_INVALID_RETURN_VALUE 错误的被拒绝的 Promise。在这两种情况下,错误处理程序将被跳过。

【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.】

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

【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.】

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

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

除了异步性质需要等待完成外,其行为与 assert.doesNotThrow() 完全相同。

【Besides the async nature to await the completion behaves identically to assert.doesNotThrow().】

import assert from 'node:assert/strict';

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

(async () => {
  await assert.doesNotReject(
    async () => {
      throw new TypeError('Wrong value');
    },
    SyntaxError,
  );
})();
import assert from 'node:assert/strict';

assert.doesNotReject(Promise.reject(new TypeError('Wrong value')))
  .then(() => {
    // ...
  });const assert = require('node:assert/strict');

assert.doesNotReject(Promise.reject(new TypeError('Wrong value')))
  .then(() => {
    // ...
  });