Clean β’ Professional
Unit testing is a crucial step in developing robust React applications. It helps you test individual React components and ensures they behave as expected before deployment. In this tutorial, youβll learn how to write clean and effective unit tests using Jest, the most popular testing framework for React.
Unit testing focuses on testing the smallest parts of your applicationβlike components or functionsβin isolation. By writing unit tests for your React components, you can:
Jest is fast, reliable, and easy to use. It comes with React out-of-the-box when using Create React App (CRA) and offers:
If you are using Create React App, Jest is already installed. For custom setups:
npm install --save-dev jest @testing-library/react @testing-library/jest-dom
@testing-library/react helps render and test React components.@testing-library/jest-dom provides custom matchers for DOM assertions.Add the following in your package.json to run tests:
"scripts": {
"test": "jest"
}
Suppose you have a simple React component:
// Greeting.jsx
import React from "react";
function Greeting({ name }) {
return <h1>Hello, {name}!</h1>;
}
export default Greeting;
Unit Test with Jest:
// Greeting.test.jsx
import React from "react";
import { render, screen } from "@testing-library/react";
import Greeting from "./Greeting";
test("renders the greeting message correctly", () => {
render(<Greeting name="Alice" />);
const greetingElement = screen.getByText("Hello, Alice!");
expect(greetingElement).toBeInTheDocument();
});
render() mounts the component in a virtual DOM.screen.getByText() finds the text content in the component.expect(...).toBeInTheDocument() asserts that the component renders correctly.You can also test dynamic behavior, like button clicks:
// Counter.jsx
import React, { useState } from "react";
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<h1>Count: {count}</h1>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
export default Counter;
Unit Test for Counter Component:
// Counter.test.jsx
import React from "react";
import { render, screen, fireEvent } from "@testing-library/react";
import Counter from "./Counter";
test("increments count when button is clicked", () => {
render(<Counter />);
const button = screen.getByText("Increment");
fireEvent.click(button);
expect(screen.getByText("Count: 1")).toBeInTheDocument();
});
fireEvent.click(button) simulates a user click.