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

Hàm assert.notEqual() 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. Hàm assert.notEqual kiểm tra hai đối tượng không được bằng nhau. Lỗi khẳng định được ném ra nếu cả hai đối tượng bằng nhau.

Cú pháp

assert.notEqual(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 notEqual.js và sao chép đoạn mã dưới. Sau khi tạo file, dùng lệnh sau để chạy:

node notEqual.js

notEqual.js

// Importing the module const assert = require('assert').strict; var a = 3; var b = "3"; try { // Checking if a & b are equal assert.notEqual(a, b); console.log("a & b are not equal"); } catch(error) { console.log("Error Occured: ", error); }

Đầu ra

C:\home\node>> node notEqual.js a & b are not equal

Ví dụ khác

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

// Import the module const assert = require('assert').strict; var a = 3; var b = 3; try { // Checking if a & b are equal assert.notEqual(a, b); console.log("a & b are not equal"); } catch(error) { console.log("Error Occured: ", error); }

Đầu ra

C:\home\node>> node notEqual.js Error Occured: { AssertionError [ERR_ASSERTION]: Identical input passed to notStrictEqual: 3 at Object. (/home/node/test/assert.js:10: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: 3, expected: 3, operator: 'notStrictEqual' }