Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

ฟังก์ชัน assert.ok() ใน Node.js

ฟังก์ชัน assert.ok ทดสอบว่าค่าเป็น truthy หรือไม่ หากเป็น falsy จะโยน AssertionError คล้ายกับ assert(value) แต่ชัดเจนกว่า

ไวยากรณ์

assert.ok(value, [message])

พารามิเตอร์

  • value – ค่าที่จะตรวจสอบ
  • message – ข้อความเมื่อค่าเป็น falsy (ทางเลือก)

ตัวอย่าง: ค่าเป็น truthy

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

try {
  assert.ok(typeof 21 === 'number');
  console.log("NO ERROR!");
} catch (error) {
  console.log("Error: ", error);
}

ผลลัพธ์

NO ERROR!

ตัวอย่าง: ค่าเป็น falsy

try {
  assert.ok(typeof 21 === 'string');
  console.log("NO ERROR!");
} catch (error) {
  console.log("Error: ", error);
}

ผลลัพธ์

Error: {
  AssertionError [ERR_ASSERTION]: The expression evaluated to a falsy value:
  assert.ok(typeof 21 === 'string')
  ...
  operator: '=='
}