第11章:测试与调试
使用 Jest 或 Mocha 测试 TypeScript 代码
1. 测试框架的选择与配置
Jest 配置
- 安装依赖
npm install --save-dev jest ts-jest @types/jest - 配置文件 (
jest.config.js)module.exports = { preset: 'ts-jest', testEnvironment: 'node', testMatch: ['**/*.test.ts'], }; - 支持 TypeScript
通过ts-jest实现类型检查与转译。
Mocha 配置
- 安装依赖
npm install --save-dev mocha chai @types/mocha @types/chai ts-node - 运行脚本 (
package.json)"scripts": { "test": "mocha -r ts-node/register 'test/**/*.test.ts'" }
2. 编写测试用例
示例:测试一个 TypeScript 函数
// src/math.ts
export function add(a: number, b: number): number {
return a + b;
}
Jest 测试文件
// test/math.test.ts
import { add } from '../src/math';
describe('add function', () => {
it('should return 3 for 1 + 2', () => {
expect(add(1, 2)).toBe(3);
});
});
Mocha + Chai 测试文件
// test/math.test.ts
import { expect } from 'chai';
import { add } from '../src/math';
describe('add function', () => {
it('should return 3 for 1 + 2', () => {
expect(add(1, 2)).to.equal(3);
});
});
3. 高级测试技巧
模拟依赖(Mocking)
- Jest 的自动模拟
jest.mock('../src/logger'); - 手动模拟
const mockFn = jest.fn(() => 'mocked value');
异步测试
// 使用 async/await
it('should resolve with data', async () => {
const result = await fetchData();
expect(result).toEqual({ data: 'success' });
});
4. 覆盖率报告
Jest 配置
// jest.config.js
module.exports = {
collectCoverage: true,
coverageDirectory: 'coverage',
};
运行 npx jest --coverage 生成 HTML 报告。
Mocha + Istanbul/NYC
npm install --save-dev nyc
npx nyc mocha -r ts-node/register 'test/**/*.test.ts'
5. 常见问题与解决
- 类型错误
确保测试文件和源码共享相同的tsconfig.json。 - 路径别名问题
在 Jest 中配置moduleNameMapper:moduleNameMapper: { '^@/(.*)$': '<rootDir>/src/$1', } - ESM 支持
对于 ES 模块,需额外配置transform和extensionsToTreatAsEsm。
总结
| 工具 | 优势 | 适用场景 |
|---|---|---|
| Jest | 开箱即用、内置 Mock | 全栈/React 项目 |
| Mocha | 灵活、可搭配多种断言库 | 需要定制化配置的项目 |
通过合理选择工具链并遵循类型安全的测试实践,可以显著提升 TypeScript 项目的可靠性。
