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


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

如果 asyncFn 是函数并且它同步抛出错误,则 assert.doesNotReject() 将返回使用使用该错误拒绝的 Promise。 如果函数没有返回 promise,则 assert.doesNotReject() 将返回使用 ERR_INVALID_RETURN_VALUE 错误拒绝的 Promise。 在这两种情况下,都会跳过错误句柄。

使用 assert.doesNotReject() 实际上没有用,因为捕获拒绝然后再次拒绝它几乎没有什么好处。 相反,请考虑在特定代码路径旁边添加不应拒绝的注释,并尽可能使错误消息具有表现力。

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

除了等待完成的异步性质外,其行为与 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(() => {
    // ...
  });

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().

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