Testing a React app with Jest and React Testing Library involves setting up a testing environment and writing test cases to ensure your components work as expected. Here's a step-by-step guide:
Setup:-
Install Jest and React Testing Library:
npm install --save-dev jest @testing-library/react @testing-library/jest-dom -
Configure Jest:
Create a
jest.config.jsfile at the root of your project or add configurations inpackage.json:{ "jest": { "preset": "react-scripts" } }
-
Create a Test File:
For a component named
ExampleComponent, create aExampleComponent.test.jsfile. -
Import Required Dependencies:
import React from 'react'; import { render, screen } from '@testing-library/react'; import ExampleComponent from './ExampleComponent'; // Import the component to be tested - >
Write Test Cases:
-
Render Test:
Test if the component renders properly:
test('renders ExampleComponent', () => { render(<ExampleComponent />); const componentElement = screen.getByTestId('example-component'); // Use appropriate selector expect(componentElement).toBeInTheDocument(); }); -
Interaction Test:
Test user interaction:
test('clicking button changes text', () => { render(<ExampleComponent />); const buttonElement = screen.getByRole('button'); const textElement = screen.getByTestId('text-element'); expect(textElement).toHaveTextContent('Initial Text'); userEvent.click(buttonElement); expect(textElement).toHaveTextContent('Updated Text'); });
-
Render Test:
-
Run Tests:
Execute tests using the Jest CLI or through your package.json script:
npm test
-
Queries:
Use
screenfrom@testing-library/reactto query elements by text, role, label, or any other accessible way. -
Assertions:
Leverage
expectfrom Jest to make assertions about the DOM elements. -
Async Testing:
For async code, use
async/awaitor return Promises within your tests.
-
Mocking Dependencies:
Use
jest.mock()to mock external dependencies like API calls or modules. -
Mock Functions:
Use
jest.fn()to create mock functions and spy on function calls.
-
Cleanup After Tests:
If your tests render components that might affect other tests, use
cleanup()from@testing-library/reactto clean up after each test.
This setup and structure provide a solid foundation for testing React components. React Testing Library focuses on testing components as users would interact with them, promoting good testing practices and maintainable tests.