ข้ามไปยังเนื้อหา

Built-in Test Runner

ตั้งแต่ 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:

math.test.js
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:

Terminal window
node --test math.test.js

หรือรันไฟล์ *.test.js ทั้งหมดแบบ recursive:

Terminal window
node --test

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']);
});
});
Terminal window
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 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);
});
import assert from 'node:assert/strict';
assert.equal(actual, expected); // == (strict: ===)
assert.notEqual(actual, expected); // !==
assert.deepEqual(obj1, obj2); // deep structural equality
assert.notDeepEqual(obj1, obj2);
assert.throws(fn, /pattern/); // fn ต้อง throw error ที่ตรงกัน
assert.rejects(asyncFn, /pattern/); // async fn ต้อง reject
assert.ok(value); // ตรวจสอบ truthy

ควรใช้ node:assert/strict เสมอแทนที่จะใช้ node:assert เพราะ strict variant ใช้ === สำหรับการเปรียบเทียบ scalar และหลีกเลี่ยงความผิดพลาดจาก type coercion

snippet ด้านล่างเป็น node:test mini-suite ที่ทำงานได้เอง รันในโหมด node เพื่อดู TAP output จริง:

Node.js

Needs the Node.js runtime — open in StackBlitz to run.

Terminal window
# Watch mode — รัน test ใหม่เมื่อไฟล์เปลี่ยน (Node 22+)
node --test --watch
# รันเฉพาะ test ที่ตรงกับ pattern
node --test --test-name-pattern "Array"
# รายงาน code coverage (Node 22+)
node --test --experimental-test-coverage
# รัน test files แบบ parallel (ค่าเริ่มต้นใน Node 22+)
node --test --test-concurrency=4
import ใดที่ให้ `test()` และ `describe()` ใน Node.js โดยไม่ต้องติดตั้งอะไรเพิ่ม?
จะรันไฟล์ `*.test.js` ทั้งหมดในโปรเจกต์แบบ recursive ได้อย่างไร?
จะเกิดอะไรขึ้นเมื่อ async test function reject promise?
ทำไมควรใช้ `node:assert/strict` แทน `node:assert`?