開新的 Node.js 專案,習慣先裝 jest、nodemon、dotenv。這三個功能 Node.js 現在都內建了,小型專案和工具程式可以一個套件都不裝。
以下在 Node.js 26.13 實測。
測試:node:test
// price.mjs
export function totalPrice(items, { taxRate = 0.05 } = {}) {
if (!Array.isArray(items)) throw new TypeError('items must be an array');
const subtotal = items.reduce((sum, { price, qty }) => sum + price * qty, 0);
return Math.round(subtotal * (1 + taxRate));
}
// price.test.mjs
import { test, describe } from 'node:test';
import assert from 'node:assert/strict';
import { totalPrice } from './price.mjs';
describe('totalPrice', () => {
test('加總並含稅', () => {
assert.equal(totalPrice([{ price: 100, qty: 2 }, { price: 50, qty: 1 }]), 263);
});
test('可以指定稅率', () => {
assert.equal(totalPrice([{ price: 100, qty: 1 }], { taxRate: 0 }), 100);
});
test('空陣列是 0', () => {
assert.equal(totalPrice([]), 0);
});
test('不是陣列就丟 TypeError', () => {
assert.throws(() => totalPrice(null), TypeError);
});
});
執行 node --test,它會自動找出 *.test.mjs 等符合命名規則的檔案:
$ node --test
▶ totalPrice
✔ 加總並含稅 (1.210968ms)
✔ 可以指定稅率 (3.865149ms)
✔ 空陣列是 0 (0.235451ms)
✔ 不是陣列就丟 TypeError (0.677194ms)
✔ totalPrice (7.92899ms)
✔ mock 計時器 (1.482496ms)
ℹ tests 5
ℹ suites 1
ℹ pass 5
ℹ fail 0
把預期值故意改錯,失敗訊息會標出位置與差異:
✖ 加總並含稅 (2.343182ms)
AssertionError [ERR_ASSERTION]: Expected values to be strictly equal:
263 !== 262
記得引入 node:assert/strict,不是 node:assert。後者的 equal 是寬鬆比較,assert.equal(1, '1') 會通過。
mock 計時器
上面輸出中的「mock 計時器」測試,用內建的 mock 讓 60 秒的 setTimeout 立刻觸發:
test('mock 計時器', (t) => {
t.mock.timers.enable({ apis: ['setTimeout'] });
const fn = t.mock.fn();
setTimeout(fn, 60_000);
t.mock.timers.tick(60_000);
assert.equal(fn.mock.callCount(), 1);
});
t.mock.fn() 建立可檢查呼叫次數與參數的假函式,t.mock.method() 可以替換物件上的方法,測試結束會自動還原。
開發時自動重啟:--watch
node --watch server.mjs
存檔後自動重新執行:
v1 14:06:41
Completed running 'watched.mjs'. Waiting for file changes before restarting...
Change detected in '.../watched.mjs'
Restarting 'watched.mjs'
v2 14:06:42
預設監看執行的檔案以及它 import 的所有檔案。要額外監看其他路徑,加上 --watch-path=./src。
載入 .env:--env-file
# .env
PORT=18084
API_KEY=dev-key-123
# 註解會被忽略
GREETING="hello world"
$ node app.mjs
PORT = undefined
API_KEY = undefined
GREETING = undefined
$ node --env-file=.env app.mjs
PORT = 18084
API_KEY = dev-key-123
GREETING = hello world
三個要注意的行為
shell 已經設定的變數優先,.env 不會覆蓋:
$ API_KEY=from-shell node --env-file=.env app.mjs
API_KEY = from-shell
這和 dotenv 的預設行為一樣,正式環境在系統層設定的值不會被專案裡的檔案蓋掉。
檔案不存在時,--env-file 直接結束程式:
$ node --env-file=.env.missing app.mjs
node: .env.missing: not found
選用的檔案改用 --env-file-if-exists,找不到只會提示,繼續執行:
$ node --env-file-if-exists=.env.missing app.mjs
.env.missing not found. Continuing without it.
在程式裡載入,用 process.loadEnvFile('.env')。
寫進 package.json
{
"scripts": {
"dev": "node --watch --env-file-if-exists=.env server.mjs",
"test": "node --test",
"test:watch": "node --test --watch"
}
}
什麼時候還是需要套件
- 需要快照測試、豐富的 matcher、大量現成外掛時,Jest 或 Vitest 仍然比較方便。
- 前端專案已經用 Vite,測試用 Vitest 可以共用設定。
.env需要變數展開(例如URL=http://${HOST})或多層設定檔合併時,內建功能不夠。
工具程式、小型 API、函式庫,內建功能通常就夠了。
發表留言