Node.js 中的 assert.deepStrictEqual() 函式


assert 模組提供了許多用於函式斷言的不同功能。其中之一是 deepStrictEqual() 函式。此函式用於測試實際引數和預期引數之間的深層相等性。如果未滿足條件,將引發斷言錯誤。

語法

assert.deepStrictEqual(actual, expected[, message])

引數

上述引數的說明如下 −

  • actual(實際)– 這是將針對預期引數進行評估的實際值。

  • expected(預期)– 這是與實際值進行匹配的預期引數值。

  • message(訊息)– 如果實際引數和預期引數不匹配,此引數將儲存要列印的字串訊息值。這是一個可選欄位。

安裝 Assert 模組

npm install assert

assert 模組是內建的 Node.js 模組,因此也可以跳過此步驟。可以使用以下命令檢查 assert 版本,以獲取最新的 assert 模組。

npm version assert

將模組匯入函式

const assert = require("assert");

示例

建立一個名為 – assertDeepStrict.js 的檔案,並複製以下程式碼片段。建立檔案後,使用以下命令執行此程式碼。

node assertDeepStrict.js

assertDeepStrict.js

// Importing the assert module
const assert = require('assert').strict;

try {
   // Calling the deep strict function
   assert.deepStrictEqual({ a: 3 }, { a: '3' });
   console.log("No Error Occured...")
} catch(error) {
   console.log("Error: ", error)
}

輸出

C:\home
ode>> node assertDeepStrict.js Error: { AssertionError [ERR_ASSERTION]: Input A expected to strictly deepequal input B: + expected - actual    {       - a: 3       + a: '3'    }    at Object.<anonymous> (/home/node/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: 3 }, expected: { a: '3' }, operator: 'deepStrictEqual' }

我們可以在上面的示例中看到,一個值是整數,而另一個值是字串。因此,該方法丟擲了上述錯誤。

示例

我們再看一個示例。

// Importing the assert module
const assert = require('assert').strict;

try {
   // Calling the deep strict function
   // Both the values are string
   assert.deepStrictEqual({ a: '3' }, { a: '3' });
   console.log("No Error Occured...")
} catch(error) {
   console.log("Error: ", error)
}

輸出

C:\home
ode>> node assertDeepStrict.js No Error Occured...

更新日期:20-May-2021

206 瀏覽

開啟您的 職業生涯

完成該培訓課程即可獲得認證

開始學習
廣告
© . All rights reserved.