Skip to content

Assert Module (ตรวจสอบเงื่อนไข)

ทำไม assert ถึงสำคัญ?

assert คือเครื่องมือที่ช่วยให้เราตรวจสอบความถูกต้องของโค้ดระหว่างพัฒนา ถ้าเงื่อนไขผิดจะหยุดโปรแกรมทันที (throw AssertionError) ป้องกัน bug หลุดไป production เหมาะกับมือใหม่ที่ต้องการเข้าใจพื้นฐานการทดสอบและ debug อย่างง่าย

  • ใช้ assert ตรวจสอบค่าระหว่างรันโปรแกรม (runtime check)
  • ใช้ assert เขียน unit test เบื้องต้นได้เลย
  • ช่วยให้เข้าใจหลักการ test-driven development (TDD)
  • ถ้าเข้าใจ assert จะต่อยอดไปใช้ testing framework ได้ง่ายขึ้น

แนะนำ assert module

assert เป็น built-in module สำหรับตรวจสอบเงื่อนไขใน Node.js ถ้าเงื่อนไขไม่เป็นจริงจะเกิด error ทันที (AssertionError)

หมายเหตุ: ตั้งแต่ Node.js 14+ สามารถใช้ ESM (import) ได้เลย ไม่ต้อง require


ฟังก์ชันหลักที่ใช้บ่อย (พร้อมตัวอย่าง ESM)

1. assert.strictEqual(actual, expected)

ตรวจสอบว่า actual === expected (เปรียบเทียบแบบ strict)

js
import assert from "node:assert/strict";

assert.strictEqual(1 + 1, 2); // ผ่าน ไม่มี error
assert.strictEqual(1 + 1, 3); // AssertionError: Expected values to be strictly equal
  • ถ้าเท่ากันจะผ่าน ถ้าไม่เท่ากันจะ throw error ทันที

2. assert.ok(value)

ตรวจสอบว่า value เป็น truthy

js
import assert from "node:assert/strict";

assert.ok(true); // ผ่าน
assert.ok(1); // ผ่าน
assert.ok(false); // AssertionError
  • ใช้เช็กเงื่อนไขทั่วไป เช่น ตัวแปรต้องไม่เป็น null/undefined/false

3. assert.deepStrictEqual(actual, expected)

ตรวจสอบว่า object หรือ array เท่ากันแบบลึก (deep compare)

js
import assert from "node:assert/strict";

assert.deepStrictEqual([1, 2], [1, 2]); // ผ่าน
assert.deepStrictEqual({ a: 1 }, { a: 1 }); // ผ่าน
assert.deepStrictEqual({ a: 1 }, { a: "1" }); // AssertionError
  • เหมาะกับการเปรียบเทียบโครงสร้างข้อมูลที่ซับซ้อน

ข้อควรระวัง

  • AssertionError จะหยุดโปรแกรมทันที (เหมาะกับ dev/test เท่านั้น ไม่ควรใช้ใน production logic)
  • assert ไม่เหมาะกับการ validate user input ใน production
  • ถ้าใช้กับ async function ต้องระวัง assertion ที่เกิดใน callback อาจไม่ถูกจับโดย test runner

ตัวอย่างการใช้งานจริง

1. ตรวจสอบค่าระหว่าง debug

js
import assert from "node:assert/strict";
const result = someFunction();
assert.ok(result !== null, "result ต้องไม่เป็น null");

2. เขียน unit test เบื้องต้น

js
import assert from "node:assert/strict";
function sum(a, b) {
  return a + b;
}
assert.strictEqual(sum(2, 3), 5);

3. ใช้ assert ใน script ที่ต้องการหยุดทันทีเมื่อผิดเงื่อนไข

js
import assert from "node:assert/strict";
const config = loadConfig();
assert.ok(config.apiKey, "ต้องตั้งค่า apiKey ก่อนใช้งาน");

สรุป

assert คือเครื่องมือสำคัญสำหรับมือใหม่ Node.js ช่วยตรวจสอบความถูกต้องของโค้ดได้ง่ายและปลอดภัย เหมาะกับการ debug และเขียน unit test เบื้องต้น


อ้างอิง