Computer >> Máy Tính >  >> Lập trình >> Javascript

Hàm khẳng định.notEqual () trong Node.js

Mô-đun khẳng định cung cấp một loạt các chức năng khác nhau được sử dụng để xác nhận chức năng. Kiểm tra khẳng định.notEqual rằng hai đối tượng không được bằng nhau. Lỗi xác nhận được đưa ra nếu cả hai đối tượng đều bằng nhau.

Cú pháp

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

Tham số

Các thông số trên được mô tả như bên dưới -

  • thực tế - Tham số này chứa giá trị thực tế cần được so sánh.

  • dự kiến ​​ - Tham số này sẽ giữ các giá trị mong đợi được đánh giá giống với các tham số thực tế.

  • tin nhắn - Đây là một tham số tùy chọn. Đây là thông báo do người dùng xác định được in khi chức năng được thực thi.

Cài đặt Mô-đun Assert

npm install assert

Mô-đun khẳng định là một mô-đun Node.js có sẵn, vì vậy bạn cũng có thể bỏ qua bước này. Bạn có thể kiểm tra phiên bản xác nhận bằng cách sử dụng lệnh sau để tải mô-đun xác nhận mới nhất.

npm version assert

Nhập mô-đun trong chức năng của bạn

const assert = require("assert").strict;

Ví dụ

Tạo tệp với tên - notDeepStrictEqual.js và sao chép đoạn mã bên dưới. Sau khi tạo tệp, hãy sử dụng lệnh dưới đây để chạy mã này.

node notEqual.js

notDeepStrictEqual.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ụ

Hãy xem thêm một ví dụ.

// 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.<anonymous> (/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' }