乐闻世界logo
搜索文章和话题

如何在 Jest 中测试 TypeScript 项目?如何配置 ts-jest?

2月19日 19:11

在 Jest 中测试 TypeScript 项目需要正确的配置和类型支持:

1. 安装必要的依赖:

bash
npm install --save-dev jest @types/jest ts-jest @types/node

2. 配置 Jest:

javascript
// jest.config.js module.exports = { preset: 'ts-jest', testEnvironment: 'node', roots: ['<rootDir>/src'], testMatch: ['**/__tests__/**/*.ts', '**/?(*.)+(spec|test).ts'], transform: { '^.+\\.ts$': 'ts-jest', }, collectCoverageFrom: [ 'src/**/*.ts', '!src/**/*.d.ts', ], moduleFileExtensions: ['ts', 'js', 'json'], };

3. tsconfig.json 配置:

json
{ "compilerOptions": { "types": ["jest", "node"], "esModuleInterop": true, "allowSyntheticDefaultImports": true } }

4. 编写 TypeScript 测试:

typescript
// calculator.ts export function add(a: number, b: number): number { return a + b; } // calculator.test.ts import { add } from './calculator'; describe('Calculator', () => { test('adds two numbers', () => { expect(add(2, 3)).toBe(5); }); });

5. 测试类型:

typescript
interface User { id: number; name: string; } function getUser(id: number): User { return { id, name: 'John' }; } test('returns user with correct type', () => { const user: User = getUser(1); expect(user).toEqual({ id: 1, name: 'John' }); });

6. Mock TypeScript 模块:

typescript
// api.ts export interface ApiResponse<T> { data: T; error: string | null; } export async function fetchData<T>(url: string): Promise<ApiResponse<T>> { const response = await fetch(url); const data = await response.json(); return { data, error: null }; } // api.test.ts import { fetchData } from './api'; jest.mock('./api', () => ({ fetchData: jest.fn(), })); test('fetches data', async () => { const mockData = { name: 'John' }; (fetchData as jest.Mock).mockResolvedValue({ data: mockData, error: null, }); const result = await fetchData('/api/users'); expect(result.data).toEqual(mockData); });

最佳实践:

  • 使用 ts-jest 预设简化配置
  • 确保 @types/jest 已安装
  • 使用 TypeScript 类型增强测试可读性
  • 在测试中显式声明类型
  • 使用类型安全的 Mock
  • 配置正确的路径别名
标签:Jest