Node.js 中的 assert.rejects() 函数

assert 模块提供了一系列用于函数断言的不同功能。该assert.rejects函数将等待传递的异步函数 'asyncfn' 承诺。如果 asyncfn 是一个函数,它将立即调用此函数并等待其返回的 promise 完成。然后它会检查那个被拒绝的承诺。

语法

assert.rejects(asyncfn, [error], [message])

参数

上述参数描述如下 -

  • value  – 这是一个异步函数,它将同步抛出错误。

  • error  – 此参数可以包含类、正则表达式、验证函数或将测试每个属性的对象。(可选参数)

  • message  – 这是一个可选参数。这是执行函数时打印的用户定义消息。

安装断言模块

npm install assert

assert 模块是一个内置Node.js模块,因此您也可以跳过此步骤。您可以使用以下命令检查断言版本以获取最新的断言模块。

npm version assert

在您的函数中导入模块

const assert = require("assert").strict;

示例

创建一个具有该名称的文件 -assertRejects.js并复制以下代码片段。创建文件后,使用以下命令运行此代码。

node assertRejects.js

断言拒绝.js

/// 导入模块
const assert = require('assert').strict;

(async () => {
   assert.strictEqual(21,20)
   await assert.rejects(
   async () => {
      throw new TypeError('Value passed is Incorrect !');
   },
   (err) => {
      assert.strictEqual(err.name, 'TypeError');
      assert.strictEqual(err.message, 'Incorrect value');
      return true;
   }
   ).then(() => {
      console.log("This is a reject demp")
   });
})();
输出结果
C:\home\node>> node assertRejects.js
(node:259525) UnhandledPromiseRejectionWarning: AssertionError
[ERR_ASSERTION]: Input A expected to strictly equal input B:
+ expected - actual
- 21
+ 20
   at /home/node/test/assert.js:5:9
   at Object. (/home/node/test/assert.js:18:3)
   atModule._compile(internal/modules/cjs/loader.js:778:30)
   at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
   atModule.load(internal/modules/cjs/loader.js:653:32)
   at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
   at Function.Module._load (internal/modules/cjs/loader.js:585:3)
   at Function.Module.runMain (internal/modules/cjs/loader.js:831:12)
   at startup (internal/bootstrap/node.js:283:19)
   at bootstrapNodeJSCore (internal/bootstrap/node.js:623:3)
(node:259525) UnhandledPromiseRejectionWarning: Unhandled promise rejection.
This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:259525) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate theNode.jsprocess with a non-zero exit code.

示例

让我们再看一个例子。

// 导入模块
const assert = require('assert').strict;

(async () => {
   assert.strictEqual(21,21)
   await assert.rejects(
      async () => {
         throw new TypeError('Value passed is Incorrect !');
      },
      (err) => {
         assert.strictEqual(err.name, 'TypeError');
         assert.strictEqual(err.message, 'Value passed is Incorrect !');
         return true;
      }
      ).then(() => {
         console.log("This is a reject demo success")
   });
})();
输出结果
C:\home\node>> node assertRejects.js
This is a reject demo success