Flat Preloader Icon

Testing In React

First, make sure you have Jest and React Testing Library installed in your project. You can install them using npm or yarn
				
					npm install --save-dev jest @testing-library/react @testing-library/jest-dom

				
			

Sample React Component

Let’s create a simple React component that we can test
Button.js
				
					import React from 'react';

const Button = ({ onClick, label }) => (
  <button onClick={onClick}>{label}</button>
);

export default Button;

				
			

Test File for the Component

Now, let’s create a test file for this component
Button.test.js
				
					import React from 'react';
import { render, screen, fireEvent } from '@testing-library/react';
import Button from './Button';

test('renders button with label', () => {
  render(<Button label="Click Me" />);
  const buttonElement = screen.getByText(/click me/i);
  expect(buttonElement).toBeInTheDocument();
});

test('calls onClick when button is clicked', () => {
  const handleClick = jest.fn();
  render(<Button onClick={handleClick} label="Click Me" />);
  const buttonElement = screen.getByText(/click me/i);
  fireEvent.click(buttonElement);
  expect(handleClick).toHaveBeenCalledTimes(1);
});

				
			

Running the Tests

To run the tests, you can use the following command
				
					npm test

				
			

This will start Jest and run your tests, providing feedback in the console

  • Rendering the Component:

    • render(<Button label="Click Me" />); renders the Button component with the label “Click Me”.
  • Selecting Elements:

    • screen.getByText(/click me/i); selects the button element with the text “Click Me”. The /click me/i is a regular expression that matches the text “Click Me” in a case-insensitive manner.
  • Assertions:

    • expect(buttonElement).toBeInTheDocument(); asserts that the button element is in the document.
    • expect(handleClick).toHaveBeenCalledTimes(1); asserts that the handleClick function was called exactly once.
  • Firing Events:

    • fireEvent.click(buttonElement); simulates a click event on the button element.