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

assert 模块提供了一系列用于函数断言的不同功能。在assert.ok是否值测试是真的还是假的。如果该值不为真,它将抛出断言错误。

语法

assert.ok(value, [message])

参数

上述参数描述如下 -

  • value  – 此参数将值作为输入,由 assertok()函数检查。

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

安装断言模块

npm install assert

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

npm version assert

在您的函数中导入模块

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

示例

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

node assertOk.js

断言OK.js

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

try {
   //检查值的类型
   assert.ok(typeof 21 === 'number');
   console.log("没有错误!")
} catch(error) {
   console.log("Error: ", error)
}
输出结果
C:\home\node>> node assertOk.js
没有错误!

示例

让我们再看一个例子。

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

try {
   //检查值的类型
   assert.ok(typeof 21 === 'string');
   console.log("没有错误!")
} catch(error) {
   console.log("Error: ", error)
}
输出结果
C:\home\node>> node assertOk.js
Error: { AssertionError [ERR_ASSERTION]: The expression evaluated to a falsy
value:
   assert.ok(typeof 21 === 'string')
      at Object. (/home/node/test/assert.js:6:9)
      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)
   generatedMessage: true,
   name: 'AssertionError [ERR_ASSERTION]',
   code: 'ERR_ASSERTION',
   actual: false,
   expected: true,
   operator: '==' }