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

node.jsjavascriptweb developmentfront end technology

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

语法

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

参数

上述参数描述如下 −

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

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

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

安装 Assert 模块

npm install assert

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

npm version assert

在您的函数中导入模块

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

示例

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

node assertRejects.js

assertRejects.js

/// Importing the module
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
ode>> 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)    at Module._compile (internal/modules/cjs/loader.js:778:30)    at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)    at Module.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 the Node.js process 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
ode>> node assertRejects.js This is a reject demo success

相关文章