如何使用Jest与TypeScript在代码同文件中编写并运行单元测试
在TypeScript中用Jest实现同文件编写测试(替代jest-same-file-tests)
核心思路
借助Jest的环境特性,在TypeScript源文件中编写条件执行的测试代码块——仅当运行在Jest环境时才执行测试逻辑,同时确保生产构建时自动剔除测试代码。
步骤1:编写同文件测试代码
在TS文件末尾添加测试代码块,通过typeof jest !== 'undefined'判断是否处于Jest环境:
// src/utils.ts export const add = (a: number, b: number): number => a + b // 同文件测试逻辑 if (typeof jest !== 'undefined') { describe('add函数', () => { it('返回两个数字的和', () => { expect(add(1, 2)).toBe(3) }) it('处理负数相加', () => { expect(add(-1, -2)).toBe(-3) }) }) }
步骤2:调整Jest配置
修改jest.config.js,让Jest识别源文件作为测试文件:
module.exports = { preset: 'ts-jest', testEnvironment: 'node', // 匹配所有TS文件(包括源文件) testMatch: ['**/*.ts'], // 排除无需测试的目录 testPathIgnorePatterns: ['node_modules/', 'dist/'], transform: { '^.+\\.tsx?$': 'ts-jest', }, }
步骤3:确保生产构建剔除测试代码
生产环境下,typeof jest为undefined,测试代码块不会执行。配合构建工具的tree-shaking特性(如Webpack、Rollup),这段无用代码会被自动移除。
如果用tsc直接编译,可在tsconfig.json中确保正常编译:
{ "compilerOptions": { "outDir": "./dist", "target": "ES2020", "module": "CommonJS" }, "include": ["src/**/*.ts"], "exclude": ["node_modules", "dist"] }
替代方案:使用Vitest
如果偏好更轻量的测试框架,Vitest与Jest语法完全兼容,同样支持这种同文件测试方式,只需将配置文件改为vitest.config.ts,调整对应参数即可。
内容的提问来源于stack exchange,提问作者Henry Obiaraije
相关产品推荐
相关产品推荐

