如何使用Jest为私有函数及含forEach的公共函数编写测试用例
公共函数
mapResultsToDbResponses 的Jest测试用例 先明确这个函数的核心逻辑:接收results数组,若数组存在则遍历每个元素,提取Items、Count、ScannedCount三个字段组成新数组返回;若传入null/undefined等假值,函数无返回值(返回undefined)。
针对这些场景,编写测试用例如下(假设你的类名为DbMapper,文件路径为./db-mapper.ts):
import { DbMapper } from './db-mapper'; describe('DbMapper.mapResultsToDbResponses', () => { const mapper = new DbMapper(); it('正确映射非空results数组到IDbResponse格式', () => { const mockResults = [ { Items: ['user1', 'user2'], Count: 2, ScannedCount: 10 }, { Items: [], Count: 0, ScannedCount: 5 } ]; const output = mapper.mapResultsToDbResponses(mockResults); expect(output).toEqual([ { Items: ['user1', 'user2'], Count: 2, ScannedCount: 10 }, { Items: [], Count: 0, ScannedCount: 5 } ]); expect(output.length).toBe(mockResults.length); }); it('传入空数组时返回空数组', () => { const output = mapper.mapResultsToDbResponses([]); expect(output).toEqual([]); expect(output.length).toBe(0); }); it('传入null/undefined时返回undefined', () => { const nullOutput = mapper.mapResultsToDbResponses(null as any); const undefinedOutput = mapper.mapResultsToDbResponses(undefined as any); expect(nullOutput).toBeUndefined(); expect(undefinedOutput).toBeUndefined(); }); });
Jest测试私有函数的几种方法
类的私有函数(TypeScript中private修饰的方法)无法直接被外部访问,但可以通过以下方式测试:
1. 类型断言绕过编译检查
TypeScript的私有修饰符仅在编译阶段生效,运行时私有方法依然挂载在实例上。可以通过类型断言将实例转为any来调用私有函数:
it('测试私有函数_privateProcess', () => { const mapper = new DbMapper(); // 假设私有函数_privateProcess接收一个数字参数,返回其平方值 const result = (mapper as any)._privateProcess(5); expect(result).toBe(25); });
2. 提取私有逻辑为内部导出函数
如果私有函数逻辑复杂,建议将其抽离为模块内的导出函数(仅在内部使用),类中直接调用该函数。测试时可以直接导入这个内部函数进行测试,同时对外不暴露它:
// db-mapper.ts // 内部导出,供类使用 export const _privateProcess = (num: number) => num * num; export class DbMapper { public mapResultsToDbResponses(results: any[]): IDbResponse[] { // 调用内部函数 _privateProcess(10); // ... 原有逻辑 } }
测试代码:
import { _privateProcess } from './db-mapper'; it('测试内部处理函数', () => { expect(_privateProcess(5)).toBe(25); });
3. 通过公共函数间接覆盖
私有函数的作用是支撑公共函数的逻辑,因此可以通过设计公共函数的测试用例,覆盖私有函数的所有分支场景。这种方式更符合“测试行为而非实现”的原则,避免因私有函数重构导致测试用例失效。
内容的提问来源于stack exchange,提问作者shivansh
相关产品推荐
相关产品推荐

