โมดูล assert มีฟังก์ชันสำหรับการตรวจสอบ ฟังก์ชัน assert.equal() เป็นหนึ่งในนั้น ใช้ทดสอบความเท่ากันระหว่าง actual และ expected parameters จะโยน AssertionError ถ้าเงื่อนไขไม่ผ่าน
Syntax
assert.equal(actual, expected[, message])
Parameters
พารามิเตอร์อธิบายดังนี้:
actual – ค่าจริงที่จะตรวจสอบกับ expected
expected – ค่าที่คาดหวัง ตรงกับ actual
message – ข้อความพิมพ์ถ้า actual และ expected ไม่ตรง (optional)
ติดตั้ง Assert Module
npm install assert
assert module เป็นโมดูลในตัวของ Node.js ข้ามได้ ตรวจสอบเวอร์ชัน:
npm version assert
นำเข้าโมดูล
const assert = require("assert");ตัวอย่าง
สร้างไฟล์ assertEqual.js คัดลอกโค้ด รันด้วย
node assertEqual.js
assertEqual.js
// Importing the module
const assert = require('assert').strict;
var a = 21;
var b = 20;
// Function call
try {
// Checking if both a & b are equal
assert.equal(a, b);
} catch(error) {
console.log("Error: ", error);
}Output
C:\home\node>> node assertEqual.js
Error: { AssertionError [ERR_ASSERTION]: Input A expected to strictly equal input B:
+ expected - actual
- 21
+ 20
at Object. (/home/node/mysql-test/assert.js:10:9)
...
operator: 'strictEqual' } เห็นได้ว่าค่าทั้งสองไม่เท่ากัน
ตัวอย่างเพิ่มเติม
ลองอีกตัวอย่าง
// Importing the module
const assert = require('assert');
var a = 20;
var b = '20';
// Function call
try {
// Checking if both a & b are equal
assert.equal(a, b);
console.log("a and b are equal");
} catch(error) {
console.log("Error: ", error);
}Output
C:\home\node>> node assert.js a and b are equal
เห็นได้ว่า a เป็น integer, b เป็น string แต่ค่าเท่ากัน จึงผ่าน