用 jest 写第一个单元测试只需三步:安装 jest、编写待测函数、创建测试文件并运行。1. 初始化项目并安装 jest;2. 在 math.js 中导出 add 函数;3. 在 math.test.js 中用 test 和 expect 验证结果;运行 npm test 即可看到绿色通过提示。

用 Jest 写第一个单元测试其实很简单,核心就三步:装 Jest、写一个待测函数、再写一个测试文件并运行。
1. 初始化项目并安装 Jest
确保你有 Node.js 环境,然后在项目根目录执行:
- npm init -y(快速生成 package.json)
- npm install --save-dev jest
- 在 package.json 的 scripts 中添加:
"test": "jest"
2. 写一个简单函数(比如加法)
在项目中新建 math.js:
function add(a, b) {
return a + b;
}
module.exports = { add };
3. 编写测试文件
新建 math.test.js(Jest 默认识别 *.test.js 或 *.spec.js):
const { add } = require('./math');
test('add 1 + 2 equals 3', () => {
expect(add(1, 2)).toBe(3);
});
这里 test 定义用例,expect(...).toBe(...) 是断言,检查结果是否符合预期。
4. 运行测试
终端执行:
npm test
你会看到绿色的 ✅ 提示 “1 passed”,说明测试通过。
不复杂但容易忽略:文件名必须带 .test.js 后缀,且 Jest 需要配置或默认支持 ES Module(若用 export 而非 module.exports,可加 "type": "module" 到 package.json 并改用 import)。











