To install and configure Jest and React Testing Library in a TypeScript project, follow these steps:
1. Install Dependencies
npm install --save-dev jest @types/jest @testing-library/react @testing-library/jest-dom ts-jest
2. Configure Jest
import type { Config } from '@jest/types';
const config: Config.InitialOptions = {
preset: 'ts-jest', // Use ts-jest for TypeScript
testEnvironment: 'jsdom', // Simulate a browser environment
setupFilesAfterEnv: ['@testing-library/jest-dom/extend-expect'], // Add jest-dom extensions
moduleNameMapper: {
'^@/(.*)$': '<rootDir>/src/$1', // Map aliases (if using path aliases)
},
};
export default config;
3. Update tsconfig.json{
"compilerOptions": {
"types": ["jest", "@testing-library/jest-dom"]
}
}
4. Write a Test
import React from 'react';
import { render, screen } from '@testing-library/react';
import App from './App';
test('renders learn react link', () => {
render(<App />);
const linkElement = screen.getByText(/learn react/i);
expect(linkElement).toBeInTheDocument();
});
5. Add a Test Script
{
"scripts": {
"test": "jest"
}
}
6. Run Tests
npm test