Node.js 中的 assert.notDeepEqual() 函数
node.jsjavascriptweb developmentfront end technology
assert 模块提供了一系列用于函数断言的不同功能。Assert.notDeepEqual() 检查实际参数和预期参数之间的不相等性。此外,参数不应深度相等。如果条件不满足,则会抛出错误。
语法
assert.notDeepEqual(actual, expected[, message])
参数
上述参数描述如下 −
actual – 此参数将保存需要比较的实际值。
expected –这将保存需要检查的预期参数值。
消息 ——这是一个可选参数。这是执行函数并发生任何错误时打印的用户定义消息。
安装 Assert 模块
npm install assert
assert 模块是内置的 Node.js 模块,因此您也可以跳过此步骤。您可以使用以下命令检查 assert 版本以获取最新的 assert 模块。
npm version assert
在函数中导入模块
const assert = require("assert").strict;
示例
创建一个名为 – assertNotDeepEqual.js 的文件并复制以下代码片段。创建文件后,使用以下命令运行此代码。
node assertNotDeepEqual.js
assertNotDeepEqual.js
// 导入模块 const assert = require('assert').strict; try { // Both the values should not be identical assert.notDeepEqual({ a: '21' }, { a: '21' }); } catch(error) { console.log("Error: ", error) }
输出
C:\home
ode>> node assertNotDeepEqual.js Error: { AssertionError [ERR_ASSERTION]: Identical input passed to notDeepStrictEqual: { a: '21' } at Object.<anonymous> (/home/mayankaggarwal/mysql-test/assert.js:6:9) 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) generatedMessage: true, name: 'AssertionError [ERR_ASSERTION]', code: 'ERR_ASSERTION', actual: { a: '21' }, expected: { a: '21' }, operator: 'notDeepStrictEqual' }
示例
我们再看一个例子。
// 导入模块 const assert = require('assert').strict; try { // Both the values should not be identical assert.notDeepEqual({ a: 21 }, { a: '21' }); console.log("Values are not identical") } catch(error) { console.log("Error: ", error) }
输出
C:\home
ode>> node assertNotDeepEqual.js Values are not identical
We can see in the above example that one value is of type string whereas the other value is of type integer which is why they are not equal.