They both are tools for testing React applications.
Jest is a JavaScript testing framework that helps you write and run tests for your code. It has everything you need to test React applications, including:
Test runner: Runs tests and shows the results in a readable format.
Matchers: Functions that help check if your code is working as expected (e.g., expect(value).toBe(true)).
Mocks: Allows you to simulate functions or APIs to isolate the code you're testing.
Example:
test('adds 4 + 2 to equal 6', () => {
expect(4 + 2).toBe(6);
});
This is a simple Jest test that checks if adding 4 and 2 equals 6.
React Testing Library
React Testing Library focuses on testing how components work by simulating user interactions and verifying their behavior. It encourages testing based on how the user interacts with the app rather than testing internal details like state or methods.
Example: Suppose you have a button that updates a counter when clicked:
const Counter = () => {
const [count, setCount] = React.useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
};
You can test this component using React Testing Library:
import { render, fireEvent, screen } from '@testing-library/react';
import Counter from './Counter';
test('increments the counter', () => {
render(<Counter />);
fireEvent.click(screen.getByText(/increment/i));
expect(screen.getByText(/count: 1/i)).toBeInTheDocument();
});