How to test React components with Jest?

To test React components with Jest, follow these steps:

  1. Install Jest: If Jest is not already installed in your project, you can install it by running:
npm install --save-dev jest
  1. 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.

  2. 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(); }); });
  1. Run Jest by executing the following command in the terminal:
npm test

This will run all tests in your project and provide feedback on whether they passed or failed.

  1. Make necessary changes to your component and test cases based on the feedback received from Jest. Repeat the process until all tests pass successfully.