To test React components with Jest, follow these steps:
npm install --save-dev jest
Create a new file with the naming convention <ComponentName>.test.js
. This file should be placed in the same directory as the component you want to test.
Write test cases using Jest's testing functions such as describe
, it
, expect
, and toEqual
. Here is an example of a simple test case:
import React from 'react';
import { render, screen } from '@testing-library/react';
import MyComponent from './MyComponent';
describe('MyComponent', () => {
it('renders correctly', () => {
render(<MyComponent />);
expect(screen.getByText('Hello World')).toBeInTheDocument();
});
});
npm test
This will run all tests in your project and provide feedback on whether they passed or failed.