Unit testing in React with Jest is a powerful way to ensure your components work as expected. Here’s a quick guide on how to get started:
1. Setup
Make sure you have Jest installed. If you created your React app using Create React App, Jest is already included. Otherwise, you can install it using:
npm install --save-dev jest
2. Writing Tests
Create a test file alongside your component file (e.g., MyComponent.test.js
).
Example Component (MyComponent.js
)
import React from 'react';
const MyComponent = ({ title }) => {
return <h1>{title}</h1>;
};
export default MyComponent;
Example Test (MyComponent.test.js
)
import React from 'react';
import { render, screen } from '@testing-library/react';
import MyComponent from './MyComponent';
test('renders title', () => {
render(<MyComponent title="Hello, World!" />);
const titleElement = screen.getByText(/Hello, World!/i);
expect(titleElement).toBeInTheDocument();
});
3. Running Tests
You can run your tests using the following command:
npm test
4. Mocking Functions
If your component interacts with functions (like API calls), you can mock them:
jest.mock('../api', () => ({
fetchData: jest.fn(() => Promise.resolve({ data: 'mock data' })),
}));
5. Testing Events
You can also simulate user interactions:
import userEvent from '@testing-library/user-event';
test('button click changes text', () => {
render(<MyComponent />);
const button = screen.getByRole('button', { name: /change text/i });
userEvent.click(button);
const updatedText = screen.getByText(/new text/i);
expect(updatedText).toBeInTheDocument();
});
6. Snapshot Testing
You can create a snapshot of your component for future reference:
import { render } from '@testing-library/react';
import MyComponent from './MyComponent';
test('matches snapshot', () => {
const { asFragment } = render(<MyComponent title="Snapshot Test" />);
expect(asFragment()).toMatchSnapshot();
});
7. Code Coverage
To check code coverage, you can run:
npm test -- --coverage
Conclusion
Jest, along with React Testing Library, provides a robust set of tools to test your React components effectively. You can test rendering, user interactions, and even API calls with mocks. As you build more complex components, these testing strategies will help maintain the reliability of your application.
Top comments (0)