TypeScript是否有现成方案验证函数对象的回调断言要求?
用Jest批量测试函数对象的方案
纯JavaScript实现
直接通过遍历对象的方式批量执行测试,不用为每个函数单独写测试用例,代码复用性高。
假设你有这样的函数对象和对应的验证规则:
// 待测试的函数集合 const targetFunctions = { calculateSum: (a, b) => a + b, formatName: (first, last) => `${first} ${last}`, getConstant: () => 'fixed-value' }; // 每个函数对应的验证规则 const validationRules = { calculateSum: (fn) => { // 校验参数数量 expect(fn.length).toBe(2); // 校验返回值不为undefined expect(fn(3, 5)).toBeDefined(); // 还可以加更多断言,比如返回值类型、具体结果等 expect(typeof fn(3,5)).toBe('number'); }, formatName: (fn) => { expect(fn.length).toBe(2); expect(fn('John', 'Doe')).toBeDefined(); expect(fn('John', 'Doe')).toBe('John Doe'); }, getConstant: (fn) => { expect(fn.length).toBe(0); expect(fn()).toBeDefined(); expect(fn()).toBe('fixed-value'); } };
然后写通用测试逻辑:
describe('验证所有函数符合要求', () => { // 遍历函数对象的键值对 Object.entries(targetFunctions).forEach(([funcName, func]) => { test(`验证函数 ${funcName}`, () => { const rule = validationRules[funcName]; if (!rule) { throw new Error(`未找到函数 ${funcName} 的验证规则`); } // 执行对应验证逻辑 rule(func); }); }); });
TypeScript优化方案
如果你后续要用到TypeScript,它能帮你提前做类型校验——确保validationRules的键和targetFunctions完全一致,且每个验证函数的参数类型和对应函数匹配,避免写错函数名或者传错参数。
示例代码:
// 先提取函数对象的类型 type TargetFunctions = typeof targetFunctions; // 定义验证规则的类型,强制和函数对象的结构对齐 type ValidationRules<T> = { [Key in keyof T]: (func: T[Key]) => void; }; // 此时TS会自动校验:validationRules必须包含targetFunctions的所有键,且每个函数参数类型正确 const validationRules: ValidationRules<TargetFunctions> = { calculateSum: (fn) => { expect(fn.length).toBe(2); expect(fn(3,5)).toBeDefined(); }, formatName: (fn) => { expect(fn.length).toBe(2); expect(fn('Jane', 'Smith')).toBe('Jane Smith'); }, getConstant: (fn) => { expect(fn.length).toBe(0); expect(fn()).toBe('fixed-value'); } }; // 测试逻辑和JS基本一致,加个类型断言避免TS报错 describe('验证所有函数符合要求', () => { (Object.entries(targetFunctions) as [keyof TargetFunctions, TargetFunctions[keyof TargetFunctions]][]).forEach(([funcName, func]) => { test(`验证函数 ${funcName as string}`, () => { validationRules[funcName](func); }); }); });
扩展说明
- 验证规则里可以根据需求加任意Jest断言:比如测试函数是否抛出预期错误、异步函数的返回值、副作用(比如是否调用了其他函数)等
- 纯JS方案已经能满足核心需求,TS只是提供额外的类型安全,不用也完全没问题
内容的提问来源于stack exchange,提问作者Bruno Peixoto
相关产品推荐
相关产品推荐

