React Testing

React Testing (Jest & React Testing Library)

Testing in React ensures application stability and reliability. Jest and React Testing Library (RTL) are commonly used tools for writing unit and integration tests for React components.

Setting Up Jest & React Testing Library

Jest comes pre-installed with Create React App (CRA). If you need to install React Testing Library manually, run:

npm install –save-dev @testing-library/react @testing-library/jest-dom

👉 Ensure Your package.json Contains:

“scripts”: {
“test”: “react-scripts test”
}

Run tests using:

npm test

Writing Your First Test

A basic test ensures a React component renders correctly.

👉 Example: Testing a Button Component

📌 Button.js

import React from ‘react’;

function Button({ label }) {
return <button>{label}</button>;
}

export default Button;

📌 Button.test.js

import { render, screen } from ‘@testing-library/react’;
import Button from ‘./Button’;

test(‘renders button with label’, () => {
render(<Button label=”Click Me” />);
expect(screen.getByText(“Click Me”)).toBeInTheDocument();
});

📝 How It Works:

✔️ render() mounts the component in a virtual DOM.
✔️ screen.getByText() queries the DOM for text.
✔️ expect(…).toBeInTheDocument() asserts the presence of the element.

Testing User Interactions

Simulating user actions like clicks and inputs ensures interactive elements work as expected.

👉 Example: Testing a Counter Component

📌 Counter.js

import React, { useState } from ‘react’;

function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}

export default Counter;

📌 Counter.test.js

import { render, screen, fireEvent } from ‘@testing-library/react’;
import Counter from ‘./Counter’;

test(‘increments counter on button click’, () => {
render(<Counter />);
const button = screen.getByText(‘Increment’);
fireEvent.click(button);
expect(screen.getByText(‘Count: 1’)).toBeInTheDocument();
});

📝 Key Concepts:

✔️ fireEvent.click(button) simulates a button click.
✔️ The test checks if the counter increments correctly.

Mocking API Calls with Jest

Mocking API calls prevents real network requests during testing.

👉 Example: Fetching User Data

📌 User.js

import React, { useState, useEffect } from ‘react’;

function User() {
const [user, setUser] = useState(null);

useEffect(() => {
fetch(‘https://jsonplaceholder.typicode.com/users/1’)
.then(res => res.json())
.then(data => setUser(data));
}, []);

return <div>{user ? user.name : ‘Loading…’}</div>;
}

export default User;

📌 User.test.js

import { render, screen, waitFor } from ‘@testing-library/react’;
import User from ‘./User’;

// Mock Fetch API
global.fetch = jest.fn(() =>
Promise.resolve({
json: () => Promise.resolve({ name: ‘John Doe’ })
})
);

test(‘fetches and displays user data’, async () => {
render(<User />);
await waitFor(() => expect(screen.getByText(‘John Doe’)).toBeInTheDocument());
});

📝 Key Concepts:

✔️ jest.fn() mocks the fetch API.
✔️ waitFor() waits for asynchronous updates before running assertions.

Snapshot Testing

Snapshot tests ensure UI consistency by comparing component output to a stored reference.

👉 Example: Snapshot Test for Button Component

📌 Button.test.js

import { render } from ‘@testing-library/react’;
import Button from ‘./Button’;

test(‘matches snapshot’, () => {
const { asFragment } = render(<Button label=”Snapshot Test” />);
expect(asFragment()).toMatchSnapshot();
});

📝 Key Concepts:

✔️ asFragment() captures the component’s rendered output.
✔️ Jest stores a snapshot and compares it with future renders.

Best Practices for Testing in React

✅ Test Behavior, Not Implementation – Focus on what the user sees.
✅ Use screen Queries – Prefer screen.getByText() over container.querySelector().
✅ Mock External Dependencies – Prevent flaky network-dependent tests.
✅ Use waitFor() for Async Code – Ensure API responses are handled properly.
✅ Write Descriptive Test Cases – Make tests easy to understand.
✅ Run Tests Frequently – Catch issues early during development.

Conclusion

Jest and React Testing Library provide powerful tools for testing React applications. By writing unit, integration, and snapshot tests, developers can ensure stability, correctness, and a great user experience.

Course Video in English