You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 06:45:15