โมดูล assert มีฟังก์ชันสำหรับการตรวจสอบ assert.doesNotThrow จะตรวจสอบว่าฟังก์ชันไม่โยน error จะเรียก 'fn' ทันทีเมื่อ assert.doesNotThrow ถูกเรียก
Syntax
assert.doesNotThrow(fn, [error], [message])
Parameters
พารามิเตอร์อธิบายดังนี้:
fn – ฟังก์ชันที่จะถูกเรียกเมื่อ assert.doesNotThrow ทำงาน จะเรียกฟังก์ชันนี้แทนการโยน error
error – Regular expression สำหรับ error ที่ระบุ (optional)
message – ข้อความผู้ใช้กำหนด พิมพ์เมื่อฟังก์ชันทำงาน (optional)
ติดตั้ง Assert Module
npm install assert
assert module เป็นโมดูลในตัวของ Node.js ข้ามได้ ตรวจสอบเวอร์ชัน:
npm version assert
นำเข้าโมดูล
const assert = require("assert").strict;ตัวอย่าง
สร้างไฟล์ doesNotThrow.js คัดลอกโค้ด รันด้วย
node doesNotThrow.js
doesNotThrow.js
// Importing the module
const assert = require('assert').strict;
try {
// Calling the doesNotThrow method to stop throwing error
assert.doesNotThrow(
() => {
throw new TypeError('Wrong value received. Please check !');
},
);
} catch(error) {
console.log("Error:", error);
}Output
C:\home\node>> node doesNotThrow.js
Error: { AssertionError [ERR_ASSERTION]: Got unwanted exception. Actual message: "Wrong value received. Please check !"
at Object. (/home/node/test/assert.js:6:9)
...
operator: 'doesNotThrow' }ตัวอย่างเพิ่มเติม
ลองอีกตัวอย่าง
// Importing the module
const assert = require('assert').strict;
try {
assert.doesNotThrow(
() => {
throw new TypeError('Value passed is wrong !!');
},
/abcd/,
'Whoops'
);
} catch(error) {
console.log("Error:", error);
}Output
C:\home\node>> node doesNotThrow.js
Error: TypeError: Value passed is wrong !!
at assert.doesNotThrow (/home/node/test/assert.js:7:9)
...