本文介绍使用Jest进行JavaScript单元测试,涵盖基础测试、mock函数、模块模拟及高级技巧;2. 通过示例展示如何用expect、jest.fn()、jest.mock()和jest.spyOn隔离依赖并验证行为;3. 强调测试应关注行为而非实现,建议合理使用mock并清理状态以确保可靠性。

测试驱动开发(TDD)在现代 JavaScript 开发中扮演着重要角色,而 Jest 作为目前最流行的测试框架之一,提供了简洁的 API 和强大的功能,让编写单元测试变得高效且可靠。本文将介绍如何使用 Jest 编写高质量的单元测试,并掌握关键的 mock 技巧。
单元测试关注的是最小可测代码单元,比如一个函数或类方法。Jest 提供了开箱即用的体验,无需复杂配置即可运行测试。
安装 Jest:
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 的 expect().toBe() 使用严格相等,适合基本类型比较。
在真实项目中,函数常依赖外部模块、API 或定时器。使用 mock 可以隔离这些依赖,确保测试只关注当前逻辑。
Jest 提供 jest.fn() 创建模拟函数:
test('calls callback once', () => { const mockFn = jest.fn(); someFunction(mockFn); expect(mockFn).toHaveBeenCalledTimes(1); });你还可以为 mock 函数指定返回值:
mockFn.mockReturnValue('hello'); expect(mockFn()).toBe('hello');查看调用参数也很方便:
expect(mockFn).toHaveBeenCalledWith('arg1');当你的代码引入了外部库(如 axios、fs),可以用 jest.mock() 替换整个模块。
// api.js const axios = require('axios'); async function fetchUser(id) { const res = await axios.get(`/users/${id}`); return res.data; } // api.test.js const axios = require('axios'); jest.mock('axios'); test('fetches user data', async () => { axios.get.mockResolvedValue({ data: { id: 1, name: 'John' } }); const user = await fetchUser(1); expect(user.name).toBe('John'); expect(axios.get).toHaveBeenCalledWith('/users/1'); });这里通过 mockResolvedValue 模拟异步成功响应,避免真实网络请求。
合理使用 mock 能提升测试效率,但过度使用可能导致测试脆弱。以下是一些实用建议:
基本上就这些。Jest 让 JavaScript 单元测试变得直观且强大。掌握 mock 技巧后,你能更自信地重构代码,同时保障功能正确性。测试不是负担,而是开发节奏的稳定器。
以上就是JavaScript 测试驱动:Jest 单元测试编写与 mock 技巧的详细内容,更多请关注php中文网其它相关文章!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号