Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Hàm assert.deepStrictEqual() trong Node.js

Mô tả

Module assert cung cấp nhiều chức năng khác nhau dùng cho khẳng định hàm. Một trong số đó là hàm deepStrictEqual(). Hàm này dùng để kiểm tra sự bằng nhau sâu (deep equality) giữa tham số thực tế (actual) và tham số kỳ vọng (expected). Lỗi khẳng định sẽ được ném ra nếu điều kiện không được thỏa mãn.

Cú pháp

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

Tham số

  • actual – Giá trị thực tế sẽ được đánh giá đối với tham số kỳ vọng.

  • expected – Giá trị tham số kỳ vọng được so khớp với giá trị thực tế.

  • message – Tham số chứa chuỗi thông báo được in nếu actual và expected không khớp. Là trường tùy chọn.

Cài đặt module Assert

npm install assert

Module assert là module tích hợp sẵn của Node.js, nên bạn có thể bỏ qua bước này. Bạn có thể kiểm tra phiên bản assert bằng lệnh sau để lấy module assert mới nhất.

npm version assert

Import module vào hàm

const assert = require("assert");

Ví dụ

Tạo file tên assertDeepStrict.js và sao chép đoạn mã dưới. Sau khi tạo file, dùng lệnh sau để chạy:

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); }

Đầu ra

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

Trong ví dụ trên, một giá trị là số nguyên trong khi giá trị kia là chuỗi. Do đó phương thức ném lỗi như trên.

Ví dụ khác

Xem thêm một ví dụ nữa.

// 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); }

Đầu ra

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