如何使用Jest为helper.ts中的辅助函数编写测试用例
针对getResult函数的单元测试方案
你的helper.ts中的getResult逻辑清晰,要单独验证它的执行逻辑,用Jest这类单元测试框架就能实现,核心是通过模拟函数追踪回调的触发情况。
测试文件示例(helper.test.ts)
import { getResult } from './helper'; // 创建模拟函数,用于追踪调用状态 const mockFunc1 = jest.fn(); const mockFunc2 = jest.fn(); describe('getResult function', () => { // 每次测试前重置模拟函数的调用记录,避免用例间干扰 beforeEach(() => { mockFunc1.mockClear(); mockFunc2.mockClear(); }); test('当a > b时,调用function1', () => { getResult(5, 3, mockFunc1, mockFunc2); expect(mockFunc1).toHaveBeenCalledTimes(1); expect(mockFunc2).not.toHaveBeenCalled(); }); test('当a < b时,调用function2', () => { getResult(2, 4, mockFunc1, mockFunc2); expect(mockFunc2).toHaveBeenCalledTimes(1); expect(mockFunc1).not.toHaveBeenCalled(); }); test('当a === b时,调用function2', () => { getResult(3, 3, mockFunc1, mockFunc2); expect(mockFunc2).toHaveBeenCalledTimes(1); expect(mockFunc1).not.toHaveBeenCalled(); }); });
测试逻辑说明
jest.fn()生成的模拟函数可以追踪调用次数、调用参数等关键信息beforeEach钩子在每个测试用例执行前清空调用记录,保证测试独立性- 三个测试用例覆盖了
a>b、a<b、a=b所有分支场景,确保逻辑全验证
内容的提问来源于stack exchange,提问作者Junga
相关产品推荐
相关产品推荐

