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

How to test TypeScript projects in Jest? How to configure ts-jest?

2月19日 19:11

Testing TypeScript projects in Jest requires proper configuration and type support:

1. Install Required Dependencies:

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

2. Configure 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 Configuration:

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

4. Writing TypeScript Tests:

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. Testing Types:

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 Modules:

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); });

Best Practices:

  • Use ts-jest preset to simplify configuration
  • Ensure @types/jest is installed
  • Use TypeScript types to enhance test readability
  • Explicitly declare types in tests
  • Use type-safe mocks
  • Configure proper path aliases
标签:Jest