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.notDeepEqual() kiểm tra sự không bằng nhau giữa actual và expected. Cũng như các tham số không được deep equal. Lỗi sẽ được ném ra nếu điều kiện không thỏa mãn.
Cú pháp
assert.notDeepEqual(actual, expected[, message])
Tham số
actual – Tham số giữ giá trị thực tế cần so sánh.
expected – Tham số giữ giá trị kỳ vọng cần kiểm tra.
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 và có lỗi xảy ra.
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 assertNotDeepEqual.js và sao chép đoạn mã dưới. Sau khi tạo file, dùng lệnh sau để chạy:
node assertNotDeepEqual.js
assertNotDeepEqual.js
// Importing the module 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); }Đầu ra
C:\home\node>> node assertNotDeepEqual.js Error: { AssertionError [ERR_ASSERTION]: Identical input passed to notDeepStrictEqual: { a: '21' } at Object. (/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' } Ví dụ khác
Xem thêm một ví dụ nữa.
// Importing the module 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); }Đầu ra
C:\home\node>> node assertNotDeepEqual.js Values are not identical
Trong ví dụ trên, một giá trị kiểu số nguyên, giá trị kia kiểu string, do đó chúng không bằng nhau.