Mô tả
Module assert cung cấp nhiều chức năng khác nhau dùng cho khẳng định hàm. Hàm assert.notDeepStrictEqual kiểm tra hai đối tượng không được deep strict equal. Lỗi khẳng định được ném ra nếu cả hai đối tượng bằng nhau hoàn toàn.
Cú pháp
assert.notDeepStrictEqual(actual, expected, [message])
Tham số
actual – Tham số chứa giá trị thực tế cần so sánh.
expected – Tham số giữ giá trị kỳ vọng để đánh giá lại tham số thực tế.
message – Tham số tùy chọn. Thông báo do người dùng định nghĩa được in khi hàm thực thi.
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").strict;Ví dụ
Tạo file tên notDeepStrictEqual.js và sao chép đoạn mã dưới. Sau khi tạo file, dùng lệnh sau để chạy:
node notDeepStrictEqual.js
notDeepStrictEqual.js
// Importing the module const assert = require('assert').strict; try { // Checking if actual and expected parameters are equal assert.notDeepStrictEqual({ a: '21' }, { a: '24' }); console.log("Objects are not equal"); } catch(error) { console.log("Error: ", error); }Đầu ra
C:\home\node>> node notDeepStrictEqual.js Objects are not equal
Ví dụ khác
Xem thêm một ví dụ nữa.
// Importing the module const assert = require('assert').strict; try { // Checking if actual and expected parameters are equal assert.notDeepStrictEqual({ a: '21' }, { a: '21' }); console.log("Objects are not equal"); } catch(error) { console.log("Error: ", error); }Đầu ra
C:\home\node>> node notDeepStrictEqual.js Error: { AssertionError [ERR_ASSERTION]: Identical input passed to notDeepStrictEqual: { a: '21' } at Object. (/home/node/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' }Ta thấy trong ví dụ trên cả hai giá trị đều là 21 và kiểu string.