如何在TypeScript项目中为Jest扩展toBeType类型校验断言?
如何为Jest添加
toBeType自定义匹配器(支持单个/多类型校验) 我来帮你实现一个优雅且符合Jest规范的toBeType匹配器,完美支持单个类型字符串和多类型数组的校验需求,同时完善TypeScript类型支持:
1. 扩展Jest的TypeScript类型声明
首先得让TypeScript识别这个新匹配器,我们需要扩展Jest的Matchers接口。在项目根目录或src下创建一个jest.d.ts文件:
declare global { namespace jest { interface Matchers<R> { toBeType(expected: string | string[]): R; } } } export {};
这个声明会告诉TypeScript:expect()返回的匹配器对象上存在toBeType方法,支持传入单个字符串或字符串数组作为预期类型,调用时会有完整的类型提示。
2. 实现toBeType匹配器核心逻辑
接下来编写符合Jest标准的匹配器逻辑,它会返回Jest需要的校验结果和错误提示:
const toBeType = (actual: unknown, expected: string | string[]) => { const actualType = typeof actual; let pass = false; // 处理单个预期类型的场景 if (typeof expected === 'string') { pass = actualType === expected; } // 处理多预期类型数组的场景 else if (Array.isArray(expected)) { pass = expected.includes(actualType); } // 生成友好的错误提示信息 const typeLabel = Array.isArray(expected) ? 'types' : 'type'; const message = pass ? () => `Expected value not to be of ${typeLabel} ${JSON.stringify(expected)}, but got ${actualType}` : () => `Expected value to be of ${typeLabel} ${JSON.stringify(expected)}, but got ${actualType}`; return { pass, message }; };
这个实现的优势:
- 原生支持两种调用格式,无需额外判断分支
- 错误提示清晰区分单/多类型场景,便于调试
- 完全遵循Jest自定义匹配器的规范,不直接抛出错误,让Jest统一处理测试结果
3. 注册自定义匹配器
最后把这个匹配器注册到Jest中,创建一个jest.setup.ts文件(或你已有的Jest初始化文件):
import { expect } from '@jest/globals'; expect.extend({ toBeType, });
然后在jest.config.ts里配置这个初始化文件,确保Jest启动时加载它:
export default { // 其他配置项... setupFilesAfterEnv: ['./jest.setup.ts'], };
4. 使用示例
现在你就可以像预期的那样轻松调用了:
// 单个类型校验 expect('hello world').toBeType('string'); // 测试通过 expect(123).toBeType('string'); // 测试失败,提示:Expected value to be of type "string", but got number // 多类型校验 expect({ name: 'test' }).toBeType(['string', 'object']); // 测试通过 expect(true).toBeType(['number', 'string']); // 测试失败,提示:Expected value to be of types ["number","string"], but got boolean
内容的提问来源于stack exchange,提问作者B. Bohdan
相关产品推荐
相关产品推荐

