Jest因零配置、内置断言、Mock支持、快照测试和并行执行等特性成为JavaScript测试首选,安装后通过npm test即可运行测试,其核心功能包括test/describe组织用例、expect匹配器断言、异步测试、模块Mock及快照比对,并支持生命周期钩子管理测试状态。

测试驱动开发(TDD)在现代 JavaScript 开发中扮演着关键角色,而 Jest 是目前最受欢迎的单元测试框架之一。它由 Facebook 维护,开箱即用、配置简单,支持异步测试、Mock、覆盖率报告等功能,广泛应用于 React 项目,也适用于 Node.js 和普通 JavaScript 应用。
Jest 能快速上手,主要得益于以下几个特点:
初始化项目并安装 Jest:
npm init -y npm install --save-dev jest
在 package.json 中添加测试脚本:
立即学习“Java免费学习笔记(深入)”;
"scripts": {
"test": "jest"
}
编写一个简单的函数进行测试:
// math.js
function add(a, b) {
return a + b;
}
module.exports = { add };
创建对应的测试文件:
// math.test.js
const { add } = require('./math');
test('adds 1 + 2 to equal 3', () => {
expect(add(1, 2)).toBe(3);
});
运行 npm test,Jest 会自动查找以 .test.js 或 .spec.js 结尾的文件并执行。
Jest 提供了丰富的 API 来满足不同测试需求。
1. 测试组织:test、describe使用 test() 定义单个测试用例,用 describe() 分组相关测试:
describe('Math operations', () => {
test('addition works', () => {
expect(add(1, 2)).toBe(3);
});
test('addition with negatives', () => {
expect(add(-1, -1)).toBe(-2);
});
});
Jest 使用 expect 配合匹配器进行断言:
测试 Promise 或 async/await 函数时,需返回 Promise 或使用 async:
// asyncFunc.js
function fetchData() {
return Promise.resolve('data');
}
// asyncFunc.test.js
test('fetches data asynchronously', async () => {
const data = await fetchData();
expect(data).toBe('data');
});
Mock 可替代真实实现,控制行为并验证调用:
const mockFn = jest.fn(() => 'mocked value');
mockFn('input');
expect(mockFn).toHaveBeenCalledWith('input');
expect(mockFn()).toBe('mocked value');
模拟模块导入:
// utils.js
export const fetchUser = () => axios.get('/user');
// user.test.js
jest.mock('axios');
import axios from 'axios';
import { fetchUser } from './utils';
test('fetchUser calls axios.get', async () => {
axios.get.mockResolvedValue({ data: 'fake user' });
const user = await fetchUser();
expect(axios.get).toHaveBeenCalledWith('/user');
});
用于检测输出是否意外改变:
test('renders correctly', () => {
const component = renderComponent();
expect(component).toMatchSnapshot();
});
首次运行生成快照文件,后续测试将比对结果。若变更合理,可通过交互命令更新快照。
Jest 提供钩子函数管理测试前后的状态:
例如重置 Mock 状态:
beforeEach(() => {
jest.clearAllMocks();
});
以上就是JavaScript测试驱动_Jest单元测试框架详解的详细内容,更多请关注php中文网其它相关文章!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号