assert.rejects(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 rejected.】

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

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

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

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

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

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

如果指定,当 asyncFn 未能拒绝时,message 将是 AssertionError 提供的消息。

【If specified, message will be the message provided by the AssertionError if the asyncFn fails to reject.】

import assert from 'node:assert/strict';

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

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

await assert.rejects(
  async () => {
    throw new TypeError('Wrong value');
  },
  (err) => {
    assert.strictEqual(err.name, 'TypeError');
    assert.strictEqual(err.message, 'Wrong value');
    return true;
  },
);const assert = require('node:assert/strict');

(async () => {
  await assert.rejects(
    async () => {
      throw new TypeError('Wrong value');
    },
    (err) => {
      assert.strictEqual(err.name, 'TypeError');
      assert.strictEqual(err.message, 'Wrong value');
      return true;
    },
  );
})();
import assert from 'node:assert/strict';

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

assert.rejects(
  Promise.reject(new Error('Wrong value')),
  Error,
).then(() => {
  // ...
});

error 不能是字符串。如果将字符串作为第二个参数提供,则假定已省略 error,该字符串将用于 message。这可能导致容易被忽视的错误。如果第二个参数使用字符串,请仔细阅读 assert.throws() 中的示例。