π§ͺ Introduction to Jest
Jest is a popular JavaScript testing framework developed by Meta. Itβs used for unit testing and works seamlessly with React, offering powerful features like mocking, snapshot testing, and easy configuration.
βοΈ 1. Installation
If you're using Create React App (CRA), Jest is pre-installed. Otherwise, install manually:
npm install --save-dev jest babel-jest @testing-library/react @testing-library/jest-dom
π§ͺ 2. Writing a Basic Test
Create a file like sum.test.js
:
// sum.js
export function sum(a, b) {
return a + b;
}
// sum.test.js
import { sum } from './sum';
test('adds 2 + 3 to equal 5', () => {
expect(sum(2, 3)).toBe(5);
});
π 3. Running Tests
Run the tests using the following command:
npx jest
π§© 4. Common Matchers
toBe(value)
: Exact matchtoEqual(object)
: Deep equalitytoContain(item)
: Array includes itemtoHaveLength(n)
: Array or string lengthtoThrow()
: Expect a function to throw error
πΈ 5. Snapshot Testing
Automatically track component UI output:
import { render } from '@testing-library/react';
import MyComponent from './MyComponent';
test('renders correctly', () => {
const { asFragment } = render(<MyComponent />);
expect(asFragment()).toMatchSnapshot();
});
π 6. Mocking with Jest
Jest lets you mock functions, modules, and timers. Example:
const mockFn = jest.fn();
mockFn('hello');
expect(mockFn).toHaveBeenCalledWith('hello');
π Summary
- Jest is fast, powerful, and widely used in the React ecosystem.
- Supports unit, integration, and snapshot testing.
- Works great with React Testing Library.