javascript中用jest写基础单元测试分三步:安装jest、编写可测函数、用test和expect验证行为;默认匹配*.test.js文件,支持tobe、tothrow等断言,运行npm test即可。

在 JavaScript 中用 Jest 写基础单元测试,核心是三步:安装 Jest、写可测函数、用 test 和 expect 验证行为。不需要复杂配置,开箱即用。
1. 初始化 Jest 环境
项目根目录下运行:
-
npm init -y(生成
package.json) - npm install --save-dev jest
- 在
package.json的scripts中添加:"test": "jest"
默认 Jest 会自动查找 **/*.test.js 或 **/*.spec.js 文件,无需额外配置。
2. 编写一个简单函数用于测试
比如一个计算数组最大值的函数(保存为 math.js):
Java Maven 项目审查工作流的通用输入处理。当 Java Maven 项目以 ZIP压缩包或 GitLab 仓库 URL 形式提供且需要...时使用。
function getMax(arr) {
if (!Array.isArray(arr) || arr.length === 0) {
throw new Error('Input must be a non-empty array');
}
return Math.max(...arr);
}
module.exports = { getMax };
3. 编写对应测试文件
新建 math.test.js,和 math.js 同级:
const { getMax } = require('./math');
<p>test('returns the largest number in an array', () => {
expect(getMax([1, 5, 3])).toBe(5);
});</p><p>test('throws error for empty array', () => {
expect(() => getMax([])).toThrow('Input must be a non-empty array');
});</p><p>test('handles negative numbers correctly', () => {
expect(getMax([-10, -2, -8])).toBe(-2);
});</p>
常用断言:
-
toBe(value):严格相等(===) -
toThrow(message):验证是否抛出指定错误 -
toEqual(obj):深比较对象/数组
4. 运行测试
终端执行:
- npm test —— 运行全部测试
- npm test -- --watch —— 开启监听模式,文件变化自动重跑
- npm test -- math —— 只跑包含 “math” 的测试文件
Jest 会输出每个测试是否通过,并高亮失败原因,比如期望 5 但得到 3,或错误信息不匹配。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南










