ရိုးရိုးလေး ရှင်းပြမယ်
Node test runner ကို ရိုးရိုးလေး ပြောရရင်
Test ဆိုတာ သင့် code ကို ခေါ်ပြီး ရလဒ်က မျှော်လင့်ထားတဲ့အတိုင်း ဖြစ်မဖြစ် စစ်တဲ့ code အသေးလေးတွေပါ။ Node.js မှာ test runner (node:test) နဲ့ assertion library (node:assert) ပါပြီးသားဖြစ်လို့ Jest ဒါမှမဟုတ် Mocha ကို install မလုပ်ဘဲ node --test ဆိုတဲ့ command တစ်ခုနဲ့ test တွေကို run နိုင်ပါတယ်။
စားဖိုမှူးက ဟင်းချက်ပြီးတိုင်း မြည်းကြည့်သလိုပါပဲ။ Code ပြောင်းလိုက်တိုင်း test တွေကို ပြန် run ပြီး အရင်က အလုပ်လုပ်ခဲ့တဲ့ အရာတွေ မပျက်သေးကြောင်း စက္ကန့်ပိုင်းအတွင်း သိရပါတယ်။
Problem → Why → Solution
ပြဿနာ: ခဏခဏ fail ဖြစ်တဲ့၊ ဘာမှ မစစ်တဲ့ test တွေ
Team တစ်ခုရဲ့ test suite က တကယ့် staging database နဲ့ payment sandbox ကို တိုက်ရိုက် ချိတ်ထားပါတယ်။ Run တစ်ခါကို မိနစ်အတော်ကြာပြီး network နှေးတဲ့နေ့တွေမှာ အကြောင်းမရှိဘဲ fail ဖြစ်လို့ developer တွေက ကျရှုံးတဲ့ test ကို 'ပြန် run လိုက်' လို့ပဲ ဖြေရှင်းလာကြပါတယ်။ အဆိုးဆုံးကတော့ async assertion ကို await မလုပ်ထားတဲ့ test တွေပါ — bug ရှိပေမဲ့ အစိမ်းရောင် pass ပြနေပါတယ်။
import test from 'node:test';
import assert from 'node:assert';
test('rejects an empty cart', () => {
// Not awaited and not returned: the test finishes before the promise settles.
assert.rejects(checkout([]), /cart is empty/);
});
test('charges the card', async () => {
await checkout(cart, realPaymentSandbox); // slow, flaky, costs money
});ဘာကြောင့် ဒီ test တွေ မယုံကြည်ရတာလဲ
Test တစ်ခုရဲ့ ရလဒ်က code ပေါ်မှာပဲ မူတည်သင့်ပြီး network၊ အချိန် ဒါမှမဟုတ် တခြား run တစ်ခုက ချန်ခဲ့တဲ့ data ပေါ် မမူတည်သင့်ပါဘူး။ Promise ကို await မလုပ်ရင် runner က function ပြီးသွားတာနဲ့ test ကို pass လို့ မှတ်လိုက်ပါတယ်၊ နောက်မှ ဖြစ်လာတဲ့ failure ကို test နဲ့ မဆိုင်တော့ပါဘူး။
Core concept: arrange, act, assert နဲ့ test အလွှာနှစ်ခု
test(name, fn) က test တစ်ခုကို register လုပ်ပါတယ်။ fn က throw လုပ်ရင် ဒါမှမဟုတ် ပြန်ပေးတဲ့ promise က reject ဖြစ်ရင် test fail ဖြစ်ပြီး ပြီးဆုံးသွားရင် pass ဖြစ်ပါတယ်။ describe နဲ့ it က test တွေကို အုပ်စုဖွဲ့ပေးပြီး before၊ after၊ beforeEach၊ afterEach hook တွေက setup နဲ့ cleanup ကို လုပ်ပေးပါတယ်။ File တစ်ခုထဲက test တွေက အစဉ်လိုက် run ပြီး node --test က file တစ်ခုစီကို သီးခြား process တစ်ခုစီမှာ run ပါတယ်။
Assertion တွေအတွက် node:assert/strict ကို import လုပ်ပါ။ Strict mode မှာ equal က === ကို သုံးပြီး deepEqual က type ကိုပါ စစ်ပါတယ်၊ ဒါကြောင့် "5" နဲ့ 5 ကို တူတယ်လို့ မယူဆပါဘူး။ Synchronous error အတွက် assert.throws(fn, expected) ကို သုံးပြီး promise အတွက်တော့ await assert.rejects(promise, expected) ကို သုံးပါ — await က မဖြစ်မနေ လိုပါတယ်။
Test တိုင်းက arrange (အခြေအနေကို ပြင်ဆင်)၊ act (behaviour တစ်ခုကို ခေါ်)၊ assert (မြင်နိုင်တဲ့ ရလဒ်ကို စစ်) ဆိုတဲ့ အဆင့်သုံးဆင့် ရှိပါတယ်။ Unit test တွေက pure function တွေကို memory ထဲမှာပဲ milliseconds အတွင်း စစ်ပါတယ်။ Integration test တွေကတော့ boundary ကို စစ်ပါတယ်: server.listen(0) နဲ့ OS ဆီက လွတ်နေတဲ့ port တစ်ခု တောင်းပြီး fetch နဲ့ တကယ့် HTTP request ပို့ကာ status နဲ့ JSON body ကို စစ်ပါတယ်။ Port 0 ကြောင့် test file နှစ်ခု တစ်ပြိုင်နက် run လည်း port မငြိပါဘူး။
Slow ဖြစ်တဲ့၊ ပိုက်ဆံကုန်တဲ့၊ ဒါမှမဟုတ် အပြင်မှာ ရှိတဲ့ dependency တွေကို parameter အဖြစ် လက်ခံအောင် design လုပ်ပါ။ ဒါမှ test မှာ mock.fn() နဲ့ fake တစ်ခု ထည့်ပြီး ဘယ်နှစ်ခါ၊ ဘယ် argument နဲ့ ခေါ်ခံရလဲ စစ်နိုင်ပါတယ်။
Test ကောင်းတစ်ခုက run တိုင်း အဖြေတူတူ ထွက်ပါတယ်။ Function ထဲမှာ Date.now() ကို တိုက်ရိုက် မဖတ်ဘဲ now() လို clock function ကို parameter အဖြစ် ပေးပါ၊ random value တွေကိုလည်း အပြင်ကနေ ထည့်ပေးပါ။ Test တစ်ခုက နောက် test တစ်ခု ချန်ခဲ့တဲ့ data ပေါ် မမှီခိုစေပါနဲ့ — test တစ်ခုတည်းကို သီးသန့် run ရင်လည်း pass ဖြစ်ရပါမယ်။
| အလွှာ | ဘာကို စစ်လဲ | အမြန်နှုန်း |
|---|---|---|
| Unit | Pure function တစ်ခု၊ memory ထဲမှာပဲ | Milliseconds |
| Integration | HTTP route၊ database query လို boundary တစ်ခု | Test တစ်ခုကို ms ဆယ်ဂဏန်း |
| End-to-end | Deploy လုပ်ထားတဲ့ system တစ်ခုလုံး | စက္ကန့်ပိုင်း |
- Arrange: input, fake, server(0) ပြင်
- Act: behaviour တစ်ခုကို ခေါ်
- Assert: ရလဒ်ကို strict စစ်
- Cleanup: t.after / after နဲ့ ပိတ်
Cleanup မလုပ်တဲ့ server ဒါမှမဟုတ် timer က test process ကို ထွက်မသွားအောင် ဆွဲထားပြီး suite တစ်ခုလုံးကို hang ဖြစ်စေနိုင်ပါတယ်။
အထွေထွေ ပုံစံ
import { describe, it, before, after } from 'node:test';
import assert from 'node:assert/strict';
describe('unit under test', () => {
before(async () => { /* start shared resources, e.g. server.listen(0) */ });
after(async () => { /* close them */ });
it('does one thing', () => assert.equal(actual(), expected));
it('fails loudly', async () => await assert.rejects(promise(), /message/));
});describe က အုပ်စုဖွဲ့ပြီး hook တွေက resource ကို ဖွင့်/ပိတ် လုပ်ပါတယ်။ Test တစ်ခုစီက behaviour တစ်ခုကိုပဲ စစ်ပြီး async ဖြစ်ရင် assertion ကို await လုပ်ပါ။ Command line က node --test ဖြစ်ပါတယ်။
Worked example: unit test သုံးခု၊ HTTP test တစ်ခု
ပုံမှန်အားဖြင့် pricing.mjs နဲ့ pricing.test.mjs ကို project ထဲမှာ ထားပြီး node --test နဲ့ run ပါတယ်။ ဒီ page ပေါ်မှာ example တစ်ခုတည်းနဲ့ ပြီးအောင် file နှစ်ခုကို temp folder ထဲ ရေးပြီး node:test ရဲ့ run() function နဲ့ programmatic run ပါတယ်။ run() က test event stream ကို ပြန်ပေးတဲ့အတွက် duration လို ပြောင်းလဲနေတဲ့ data မပါဘဲ ရလဒ်ကို ကိုယ်တိုင် print ထုတ်လို့ ရပါတယ်။ Test တစ်ခုကို တမင် fail ဖြစ်အောင် ရေးထားလို့ failure က ဘယ်လို ပုံစံ ရောက်လာလဲ မြင်ရပါမယ်။
import { mkdtemp, rm, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { run } from 'node:test';
// In a project these two files sit next to each other on disk and you run
// `node --test`. Here they are written to a temp folder so the demo is one file.
const dir = await mkdtemp(join(tmpdir(), 'node-test-demo-'));
await writeFile(join(dir, 'pricing.mjs'), `
export function applyDiscount(price, percent) {
if (percent < 0 || percent > 100) throw new RangeError('percent must be 0-100');
return Math.round(price * (100 - percent)) / 100;
}
`);
await writeFile(join(dir, 'pricing.test.mjs'), `
import test from 'node:test';
import assert from 'node:assert/strict';
import { createServer } from 'node:http';
import { applyDiscount } from './pricing.mjs';
test('applies a 20% discount', () => {
assert.equal(applyDiscount(50, 20), 40);
});
test('rejects an impossible percentage', () => {
assert.throws(() => applyDiscount(50, 120), RangeError);
});
test('GET /price returns the discounted price', async (t) => {
const server = createServer((req, res) => {
const base = Number(new URL(req.url, 'http://x').searchParams.get('base'));
res.setHeader('content-type', 'application/json');
res.end(JSON.stringify({ price: applyDiscount(base, 10) }));
});
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
t.after(() => server.close());
const url = 'http://127.0.0.1:' + server.address().port + '/price?base=30';
const response = await fetch(url);
assert.equal(response.status, 200);
assert.deepEqual(await response.json(), { price: 27 });
});
test('a deliberately wrong expectation', () => {
assert.equal(applyDiscount(10, 50), 4);
});
`);
let passed = 0;
let failed = 0;
for await (const { type, data } of run({ files: [join(dir, 'pricing.test.mjs')] })) {
if (data?.nesting !== 0) continue; // only top-level tests
if (type === 'test:pass') {
passed += 1;
console.log(`pass ${data.name}`);
} else if (type === 'test:fail') {
failed += 1;
const { expected, actual } = data.details.error.cause;
console.log(`FAIL ${data.name}: expected ${expected}, got ${actual}`);
}
}
console.log(`${passed} passed, ${failed} failed`);
await rm(dir, { recursive: true, force: true });Code ကို တစ်ပိုင်းချင်း ရှင်းပြမယ်
- Strict assertions
import assert from 'node:assert/strict';Strict version ကြောင့် equal က === နဲ့ နှိုင်းယှဉ်ပါတယ်။ Legacy mode ရဲ့ == ကြောင့် "40" နဲ့ 40 တူတယ်လို့ ထင်မှတ်တဲ့ အမှားမျိုး မဖြစ်တော့ပါဘူး။
- Synchronous error
assert.throws(() => applyDiscount(50, 120), RangeError);Function ကို arrow function ထဲ ထည့်ပေးရပါတယ်၊ ဒါမှ assert.throws က ကိုယ်တိုင် ခေါ်ပြီး error ကို ဖမ်းနိုင်မှာပါ။ ဒုတိယ argument က error class ကိုပါ စစ်ပါတယ်။
- Real server on a free port
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));Port 0 က OS ကို လွတ်နေတဲ့ port တစ်ခု ရွေးခိုင်းပါတယ်၊ server.address().port က ရွေးလိုက်တဲ့ နံပါတ်ကို ပြပါတယ်။
- Cleanup that always runs
t.after(() => server.close());t.after က assertion fail ဖြစ်ရင်တောင် run ပါတယ်။ Server ကို မပိတ်ရင် child process က ထွက်မသွားဘဲ suite က hang ဖြစ်ပါတယ်။
- Read the event stream
for await (const { type, data } of run({ files: [join(dir, 'pricing.test.mjs')] })) {run() က node --test လိုပဲ file ကို child process ထဲမှာ run ပြီး test:pass၊ test:fail စတဲ့ event တွေကို ထုတ်ပါတယ်။ Fail event ရဲ့ details.error.cause ထဲမှာ expected နဲ့ actual ပါပါတယ်။
pass applies a 20% discount
pass rejects an impossible percentage
pass GET /price returns the discounted price
FAIL a deliberately wrong expectation: expected 4, got 5
3 passed, 1 failedFake dependency နဲ့ async assertion
checkout က card ကို charge လုပ်တဲ့ function ကို parameter အဖြစ် လက်ခံလို့ test မှာ mock.fn() နဲ့ ဖန်တီးထားတဲ့ fake ကို ထည့်လို့ ရပါတယ်။ Fake က ခေါ်ခံရတိုင်း mock.calls ထဲ မှတ်ထားပြီး mock.callCount() က အကြိမ်ရေကို ပြပါတယ်။ ဒုတိယ test က promise rejection ကို await assert.rejects နဲ့ စစ်ပါတယ်။ ဒီ file ကို node --test နဲ့ ဒါမှမဟုတ် node နဲ့ တိုက်ရိုက် run ရင် TAP ဒါမှမဟုတ် spec format နဲ့ ရလဒ် ထွက်ပါတယ်။
// cart.test.mjs: run with `node --test`; tests in one file run in order.
import { describe, it, mock } from 'node:test';
import assert from 'node:assert/strict';
async function checkout(cart, chargeCard) {
if (cart.length === 0) throw new Error('cart is empty');
const total = cart.reduce((sum, item) => sum + item.price, 0);
await chargeCard(total);
return total;
}
describe('checkout', () => {
it('charges the card once with the total', async () => {
const chargeCard = mock.fn(async () => {}); // a fake payment gateway
const total = await checkout([{ price: 5 }, { price: 7 }], chargeCard);
assert.equal(total, 12);
assert.equal(chargeCard.mock.callCount(), 1);
assert.deepEqual(chargeCard.mock.calls[0].arguments, [12]);
});
it('rejects an empty cart', async () => {
await assert.rejects(checkout([], mock.fn()), /cart is empty/); // await it!
});
});| Command | လုပ်ဆောင်ချက် |
|---|---|
| node --test | *.test.mjs လို အမည်ပုံစံ ရှိတဲ့ file တွေကို ရှာပြီး run |
| node --test --watch | File ပြောင်းတိုင်း ပြန် run |
| node --test --test-name-pattern="discount" | နာမည် ကိုက်တဲ့ test တွေကိုပဲ run |
| node --test --experimental-test-coverage | Coverage report ထုတ် (Node 22 မှာ experimental) |
လက်တွေ့ project တွေမှာ
လက်တွေ့ project တွေမှာ test ကို ဘယ်လို စီစဉ်လဲ
API project တစ်ခုမှာ test အများစုက unit test ဖြစ်ပြီး validation၊ price calculation၊ permission rule တွေကို စစ်ပါတယ်။ Route တစ်ခုစီအတွက် integration test အနည်းငယ်က app ကို listen(0) နဲ့ ဖွင့်ပြီး status code၊ header နဲ့ error body ကို စစ်ပါတယ်။ ဒီ test တွေက pull request တိုင်းမှာ CI ထဲ run ပြီး fail ရင် merge ကို ပိတ်ထားပါတယ်။
- App ကို createApp() လို factory function ကနေ ထုတ်ပြီး listen ကို entry point မှာပဲ ခေါ်ပါ၊ ဒါမှ test က ကိုယ်ပိုင် instance ကို ဖွင့်နိုင်မှာပါ။
- Database ကို စစ်ရမယ်ဆိုရင် test တစ်ခုစီ transaction ထဲမှာ run ပြီး rollback လုပ်တာ ဒါမှမဟုတ် container ထဲက သီးခြား test database ကို သုံးတာမျိုး လုပ်ပါ — shared staging data ကို မသုံးပါနဲ့။
- Email၊ payment၊ third-party API တွေကို parameter ဒါမှမဟုတ် constructor ကနေ ထည့်ပေးပြီး test မှာ fake နဲ့ အစားထိုးပါ။
အမှားများ
Testing မှာ ဖြစ်လေ့ရှိတဲ့ အမှားများ
assert.rejects ကို await မလုပ်ခြင်း
assert.rejects က promise တစ်ခု ပြန်ပေးပါတယ်။ await ဒါမှမဟုတ် return မလုပ်ရင် test function က ချက်ချင်း ပြီးသွားပြီး test pass ဖြစ်ပါတယ်၊ နောက်မှ ဖြစ်တဲ့ failure က အဲဒီ test နဲ့ မဆိုင်တော့ပါဘူး။ Test async ဖြစ်ပြီး promise-returning assertion တိုင်းရှေ့မှာ await ရှိကြောင်း စစ်ပါ။
Fixed port နဲ့ server ကို မပိတ်ခြင်း
listen(3000) က developer machine မှာ တခြား app run နေရင် ဒါမှမဟုတ် test file နှစ်ခု တစ်ပြိုင်နက် run ရင် EADDRINUSE နဲ့ fail ဖြစ်ပါတယ်။ Server ကို မပိတ်ရင် test process က ထွက်မသွားဘဲ CI job က timeout ဖြစ်တဲ့အထိ စောင့်နေပါတယ်။ listen(0) ကို သုံးပြီး after ဒါမှမဟုတ် t.after ထဲမှာ close() ကို ခေါ်ပါ။
Implementation detail ကို စစ်ခြင်း
Private helper တစ်ခု ဘယ်နှစ်ခါ ခေါ်ခံရလဲ စစ်တဲ့ test က code ကို refactor လုပ်တိုင်း ကျိုးပြီး bug ကိုတော့ မဖမ်းပါဘူး။ Return value၊ HTTP response ဒါမှမဟုတ် အပြင်ဘက် dependency ကို ပေးလိုက်တဲ့ call လို မြင်နိုင်တဲ့ behaviour ကိုပဲ စစ်ပါ။
Mini challenge
Mini challenge: config parser နဲ့ health endpoint ကို test လုပ်ပါ
parsePort နဲ့ createApp ကို export လုပ်တဲ့ app.mjs ကို test လုပ်ပါ။ parsePort အတွက် unit test သုံးခု ရေးပြီး describe အုပ်စုတစ်ခုထဲမှာ before hook နဲ့ server ကို port 0 ပေါ် တစ်ကြိမ် ဖွင့်ကာ /health နဲ့ မရှိတဲ့ route ကို စစ်ပါ။ ပြီးရင် run() နဲ့ ရလဒ်ကို nesting အလိုက် indent လုပ်ပြီး print ထုတ်ပါ။
- parsePort: default 3000၊ "8080" → 8080၊ text ကို reject
- before မှာ server ကို listen(0) နဲ့ ဖွင့်ပြီး after မှာ close() လုပ်ပါ
- GET /health က 200 နဲ့ { ok: true }၊ မရှိတဲ့ route က 404
- test:pass နဲ့ test:fail event တွေကို data.nesting အလိုက် indent လုပ်ပြီး print ထုတ်ပါ
import { mkdtemp, rm, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { run } from 'node:test';
const dir = await mkdtemp(join(tmpdir(), 'config-tests-'));
// TODO: write app.mjs exporting parsePort(raw = '3000') and createApp()
// (createApp answers /health with {"ok":true} and everything else with 404)
// TODO: write app.test.mjs:
// describe('parsePort') with three it() cases
// describe('HTTP app') with before/after hooks and two it() cases
// TODO: for await over run({ files: [...] }) and print
// ' '.repeat(data.nesting) + (pass ? 'ok ' : 'NOT') + ' ' + data.name
// TODO: remove dirရလဒ်: Test ငါးခုလုံး ok ပြပြီး suite နှစ်ခု (parsePort နဲ့ HTTP app) ကလည်း သူတို့ရဲ့ child test တွေ ပြီးမှ indent မပါဘဲ ok ပြပါတယ်။
အရိပ်အမြွက် ကြည့်ရန်
Server ကို describe ထဲမှာ let server; let base; လို့ ကြေညာပြီး before ထဲမှာ assign လုပ်ပါ။ after ကနေ new Promise((resolve) => server.close(resolve)) ကို return ပြန်ရင် runner က server ပိတ်တဲ့အထိ စောင့်ပါတယ်။
အဖြေ ကြည့်ရန်
import { mkdtemp, rm, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { run } from 'node:test';
const dir = await mkdtemp(join(tmpdir(), 'config-tests-'));
await writeFile(join(dir, 'app.mjs'), `
import { createServer } from 'node:http';
export function parsePort(raw = '3000') {
const port = Number(raw);
if (!Number.isInteger(port) || port < 1 || port > 65535) {
throw new Error('Invalid PORT: ' + raw);
}
return port;
}
export function createApp() {
return createServer((req, res) => {
if (req.url === '/health') return res.end(JSON.stringify({ ok: true }));
res.statusCode = 404;
res.end();
});
}
`);
await writeFile(join(dir, 'app.test.mjs'), `
import { after, before, describe, it } from 'node:test';
import assert from 'node:assert/strict';
import { createApp, parsePort } from './app.mjs';
describe('parsePort', () => {
it('defaults to 3000', () => assert.equal(parsePort(undefined), 3000));
it('parses a numeric string', () => assert.equal(parsePort('8080'), 8080));
it('rejects text', () => assert.throws(() => parsePort('http'), /Invalid PORT/));
});
describe('HTTP app', () => {
let server;
let base;
before(async () => {
server = createApp();
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
base = 'http://127.0.0.1:' + server.address().port;
});
after(() => new Promise((resolve) => server.close(resolve)));
it('GET /health answers ok', async () => {
const res = await fetch(base + '/health');
assert.equal(res.status, 200);
assert.deepEqual(await res.json(), { ok: true });
});
it('unknown routes return 404', async () => {
const res = await fetch(base + '/nope');
assert.equal(res.status, 404);
});
});
`);
const results = [];
for await (const { type, data } of run({ files: [join(dir, 'app.test.mjs')] })) {
if (type === 'test:pass' || type === 'test:fail') {
const mark = type === 'test:pass' ? 'ok ' : 'NOT';
results.push(`${' '.repeat(data.nesting)}${mark} ${data.name}`);
}
}
console.log(results.join('\n'));
await rm(dir, { recursive: true, force: true });Quick Quiz 1 / 3
Quick Quiz 2 / 3
Quick Quiz 3 / 3
မှတ်ထားရမယ့် အချက်များ
- node:test နဲ့ node:assert/strict က Node.js ထဲမှာ ပါပြီးသား ဖြစ်ပြီး node --test နဲ့ run ပါတယ်။
- Promise ကို ပြန်ပေးတဲ့ assertion တွေ (assert.rejects) ကို အမြဲ await လုပ်ပါ။
- Integration test က listen(0) ပေါ်က တကယ့် server ကို fetch နဲ့ ခေါ်ပြီး after hook ထဲမှာ ပိတ်ပါတယ်။
- External dependency တွေကို parameter အဖြစ် ထည့်ပေးပြီး test မှာ mock.fn() နဲ့ အစားထိုးပါ။
Test runner — Node.js