Node.js:小工具先用内置 node:test 写个冒烟测试

33 次浏览4 条回复

写一点本地小工具时,不一定一上来就装测试框架。Node.js 自带的 node:test 可以先把最关键的函数跑起来,适合做个很轻的冒烟测试。

环境:Node.js 18+。新建两个文件:

// sum.mjs
export function sum(a, b) {
  return a + b
}
// sum.test.mjs
import test from 'node:test'
import assert from 'node:assert/strict'
import { sum } from './sum.mjs'

test('sum adds two numbers', () => {
  assert.equal(sum(2, 3), 5)
})

然后跑:

node --test sum.test.mjs

通过时会输出 TAP 格式的结果。它不花哨,但对那种只有几个纯函数的小脚本挺够用。后面项目变大了,再换 Vitest、Jest 之类也不迟。

这个适合小工具起步。补一个小点:文件多了以后可以直接跑 node --test,它会按默认规则找测试文件,不一定每次都写具体文件名。

如果想让输出更像平时看的测试结果,也可以试一下:

node --test --test-reporter=spec

小脚本里先这样兜住关键函数,确实比一开始就搭一堆东西轻。

还可以顺手把异步失败路径也测一下,很多小脚本最后都是调接口、读文件这类 Promise。

import test from 'node:test'
import assert from 'node:assert/strict'

async function mustBePositive(n) {
  if (n <= 0) throw new Error('bad number')
  return n
}

test('rejects bad input', async () => {
  await assert.rejects(() => mustBePositive(0), /bad number/)
})

这个在 Node.js 18+ 也能直接 node --test 跑。小工具里我觉得先把“正常返回”和“会不会按预期失败”各测一个,就已经能挡住不少低级改坏了。

调某个失败用例时,--test-name-pattern 也挺省事,不用临时注释一堆测试。

比如测试名里有 sum:

node --test --test-name-pattern=sum

它会只跑名称匹配的用例。小文件可能无所谓,测试文件一多,这个比改代码再改回来干净一点。

还有个容易忽略的小功能:临时只跑某个用例时可以用 test.only,不过命令也要加 --test-only。

import test from 'node:test'
import assert from 'node:assert/strict'

test.only('sum adds two numbers', () => {
  assert.equal(2 + 3, 5)
})
node --test --test-only

这样比较适合本地定位问题。提交前最好搜一下 only,不然很容易把其他测试漏跑了。