Lesson 38 of 56 · Typescript
Testing with Jest & `ts-jest`
Duration: 20 minutes
Install Jest for TypeScript
npm i -D jest ts-jest @types/jest
npx ts-jest config:init
Updates jest.config.js to use ts-jest transformer.
Simple test
// sum.ts
export const sum = (a: number, b: number) => a + b;
// sum.test.ts
import { sum } from './sum';
test('adds two numbers', () => {
expect(sum(2, 3)).toBe(5);
});
Run with npm test.
Mocking modules
jest.mock('axios');
import axios from 'axios';
(axios.get as jest.Mock).mockResolvedValue({ data: { id: 1 } });
Using expect.assertions
Ensures async assertions fire.
test('async fetch', async () => {
expect.assertions(1);
const data = await fetchData();
expect(data).toBe('done');
});