Built-in Test Runner
node:test — ครบครันในตัว
หัวข้อที่มีชื่อว่า “node:test — ครบครันในตัว”ตั้งแต่ Node 18 เป็นต้นมา คุณสามารถเขียนและรันการทดสอบได้โดยไม่ต้องพึ่ง third-party dependency เลย โมดูล node:test มี test(), describe(), it(), hooks before/after, และ output แบบ TAP ให้ใช้งาน จับคู่กับ node:assert สำหรับ assertions
โครงสร้างพื้นฐานของการทดสอบ
หัวข้อที่มีชื่อว่า “โครงสร้างพื้นฐานของการทดสอบ”ไฟล์ทดสอบคือไฟล์ .js (หรือ .mjs) ธรรมดาที่ import node:test และ node:assert:
import { test, describe, it } from 'node:test';import assert from 'node:assert/strict';
test('add returns the correct sum', function() { assert.equal(2 + 3, 5);});รันจาก terminal:
node --test math.test.jsหรือรันไฟล์ *.test.js ทั้งหมดแบบ recursive:
node --testdescribe / it — การจัดกลุ่มการทดสอบ
หัวข้อที่มีชื่อว่า “describe / it — การจัดกลุ่มการทดสอบ”describe ใช้จัดกลุ่มการทดสอบที่เกี่ยวข้องกัน ส่วน it เป็น alias ของ test ที่อ่านได้เป็นธรรมชาติมากกว่าเมื่อใช้ภายใน describe:
import { describe, it } from 'node:test';import assert from 'node:assert/strict';
describe('String utilities', function() { it('trim removes leading and trailing whitespace', function() { assert.equal(' hello '.trim(), 'hello'); });
it('split divides by delimiter', function() { assert.deepEqual('a,b,c'.split(','), ['a', 'b', 'c']); });});node --test string-utils.test.js# TAP output:# ok 1 - String utilities > trim removes leading and trailing whitespace# ok 2 - String utilities > split divides by delimiterการทดสอบแบบ Async
หัวข้อที่มีชื่อว่า “การทดสอบแบบ Async”ส่ง async function ให้กับ test หรือ it ได้เลย runner จะ await ให้ — ถ้า promise ถูก reject การทดสอบจะล้มเหลว:
import { test } from 'node:test';import assert from 'node:assert/strict';
test('fetch-like async test', async function() { const result = await Promise.resolve(42); assert.equal(result, 42);});คู่มือ node:assert/strict
หัวข้อที่มีชื่อว่า “คู่มือ node:assert/strict”import assert from 'node:assert/strict';
assert.equal(actual, expected); // == (strict: ===)assert.notEqual(actual, expected); // !==assert.deepEqual(obj1, obj2); // deep structural equalityassert.notDeepEqual(obj1, obj2);assert.throws(fn, /pattern/); // fn ต้อง throw error ที่ตรงกันassert.rejects(asyncFn, /pattern/); // async fn ต้อง rejectassert.ok(value); // ตรวจสอบ truthyควรใช้ node:assert/strict เสมอแทนที่จะใช้ node:assert เพราะ strict variant ใช้ === สำหรับการเปรียบเทียบ scalar และหลีกเลี่ยงความผิดพลาดจาก type coercion
Demo แบบ runnable
หัวข้อที่มีชื่อว่า “Demo แบบ runnable”snippet ด้านล่างเป็น node:test mini-suite ที่ทำงานได้เอง รันในโหมด node เพื่อดู TAP output จริง:
Needs the Node.js runtime — open in StackBlitz to run.
ฟีเจอร์เพิ่มเติม
หัวข้อที่มีชื่อว่า “ฟีเจอร์เพิ่มเติม”# Watch mode — รัน test ใหม่เมื่อไฟล์เปลี่ยน (Node 22+)node --test --watch
# รันเฉพาะ test ที่ตรงกับ patternnode --test --test-name-pattern "Array"
# รายงาน code coverage (Node 22+)node --test --experimental-test-coverage
# รัน test files แบบ parallel (ค่าเริ่มต้นใน Node 22+)node --test --test-concurrency=4