Jest Testing Framework
Master Jest testing framework for writing comprehensive unit tests and test utilities for React applications. This is a foundational concept in component-based UI development that professional developers rely on daily. The explanations below are written to be beginner-friendly while covering the depth and nuance that comes from real-world React experience. Take your time with each section and practice the examples
Jest Fundamentals
Jest is a JavaScript testing framework that provides a complete testing solution with built-in mocking, assertions, and test runners.. This is an essential concept that every React developer must understand thoroughly. In professional development environments, getting this right can mean the difference between code that works reliably and code that breaks in production. The following sections break this down into clear, digestible pieces with practical examples you can try immediately
Basic Jest Setup
// jest.config.js
module.exports = {
testEnvironment: 'jsdom',
setupFilesAfterEnv: ['<rootDir>/src/setupTests.js'],
moduleNameMapping: {
'^@/(.*)$': '<rootDir>/src/$1'
},
collectCoverageFrom: [
'src/**/*.{js,jsx,ts,tsx}',
'!src/**/*.d.ts'
]
};
// setupTests.js
import '@testing-library/jest-dom';Writing Tests
// Basic test example
describe('Math utilities', () => {
test('adds two numbers correctly', () => {
expect(2 + 2).toBe(4);
});
test('handles edge cases', () => {
expect(() => {
throw new Error('Something went wrong');
}).toThrow('Something went wrong');
});
});Mocking and Spies
// Mock functions
const mockFn = jest.fn();
mockFn('arg1', 'arg2');
expect(mockFn).toHaveBeenCalledWith('arg1', 'arg2');
// Mock modules
jest.mock('./api', () => ({
fetchUser: jest.fn(() => Promise.resolve({ id: 1, name: 'John' }))
}));Async Testing
// Testing async functions
test('fetches user data', async () => {
const user = await fetchUser(1);
expect(user).toEqual({ id: 1, name: 'John' });
});
// Testing promises
test('handles promise rejection', async () => {
await expect(fetchUser(999)).rejects.toThrow('User not found');
});Mini-Project: Utility Testing Suite
// Complete testing suite for utility functions
import { formatDate, validateEmail, debounce } from '../utils';
describe('Utility Functions', () => {
describe('formatDate', () => {
test('formats date correctly', () => {
const date = new Date('2023-12-25');
expect(formatDate(date)).toBe('25/12/2023');
});
test('handles invalid date', () => {
expect(formatDate('invalid')).toBe('Invalid Date');
});
});
describe('validateEmail', () => {
test('validates correct email', () => {
expect(validateEmail('test@example.com')).toBe(true);
});
test('rejects invalid email', () => {
expect(validateEmail('invalid-email')).toBe(false);
});
});
describe('debounce', () => {
test('debounces function calls', (done) => {
const mockFn = jest.fn();
const debouncedFn = debounce(mockFn, 100);
debouncedFn();
debouncedFn();
debouncedFn();
setTimeout(() => {
expect(mockFn).toHaveBeenCalledTimes(1);
done();
}, 150);
});
});
});