Jest Testing Framework
Master Jest testing framework for writing comprehensive unit tests and test utilities for React applications.
90 minโขBy Priygop TeamโขLast updated: Feb 2026
Jest Fundamentals
Jest is a JavaScript testing framework that provides a complete testing solution with built-in mocking, assertions, and test runners.
Basic Jest Setup
Example
// 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
Example
// 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
Example
// 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
Example
// 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
Example
// 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);
});
});
});