| Common React Testing Mistakes :👈 | 👉:React-QA-1 |
React Testing, Unit test, Libraries |
React Testing: Current Testing Library Recommendations
React testing should focus on what users can see and do, rather than the internal implementation of components.
A good testing strategy uses three complementary levels:
- Unit Testing: Verifies small pieces of logic independently.
- Integration Testing: Verifies that multiple parts of the application work together.
- End-to-End (E2E) Testing: Verifies complete user journeys in a real browser.
1. Difference Between Unit, Integration and E2E Testing
Consider an e-commerce React application with product search, shopping cart and checkout.
| Testing Type | What It Tests | Example |
|---|---|---|
| Unit Testing | One small unit in isolation | Test a function that calculates a product discount. |
| Integration Testing | Multiple application parts working together | Test product search, API response and product list rendering. |
| E2E Testing | A complete user journey through the application | Search for a product, add it to the cart and complete checkout. |
2. Unit Testing
Purpose: Verify that one function, component or small unit behaves correctly in isolation.
Examples:
- Verify a discount calculation function.
- Check whether a button displays the correct label based on props.
- Verify a price-formatting utility.
- Test a validation function.
Example
calculateTotal.js
export function calculateTotal(price, quantity) {
return price * quantity;
}
calculateTotal.test.js
import { describe, test, expect } from 'vitest';
import { calculateTotal } from './calculateTotal';
describe('calculateTotal', () => {
test('calculates the total price', () => {
expect(calculateTotal(100, 3)).toBe(300);
});
});
Expected result: The function returns 300 when the price is 100 and quantity is 3.
Unit tests should generally be:
- Fast.
- Focused on one responsibility.
- Independent of external services.
- Easy to understand and maintain.
3. Integration Testing
Purpose: Verify that multiple components, hooks, services and application features work together correctly.
For example, a product search feature may involve:
- A search input component.
- React state management.
- An API service.
- A product list component.
- Loading and error handling.
An integration test verifies that these pieces work together.
Example
ProductSearch.jsx
import { useState } from 'react';
export function ProductSearch({ products }) {
const [search, setSearch] = useState('');
const filteredProducts = products.filter(product =>
product.name.toLowerCase().includes(search.toLowerCase())
);
return (
<div>
<label htmlFor="search">Search products</label>
<input
id="search"
value={search}
onChange={e => setSearch(e.target.value)}
/>
<ul>
{filteredProducts.map(product => (
<li key={product.id}>{product.name}</li>
))}
</ul>
</div>
);
}
ProductSearch.test.jsx
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { test, expect } from 'vitest';
import { ProductSearch } from './ProductSearch';
test('filters products when the user searches', async () => {
const user = userEvent.setup();
const products = [
{ id: 1, name: 'Laptop' },
{ id: 2, name: 'Mobile' },
{ id: 3, name: 'Keyboard' }
];
render(<ProductSearch products={products} />);
await user.type(
screen.getByRole('textbox', { name: /search products/i }),
'Laptop'
);
expect(screen.getByText('Laptop')).toBeInTheDocument();
expect(screen.queryByText('Mobile')).not.toBeInTheDocument();
});
What does this test verify?
- The component renders correctly.
- The input accepts user interaction.
- React state updates.
- The filtering logic works.
- The UI displays the expected result.
This is a component-level integration test because it verifies the interaction between the input, state and rendered product list.
Other integration testing examples:
- Login form + authentication service + navigation.
- Redux store + connected components.
- Context Provider + consuming components.
- Form submission + API response + success message.
- React Router + page components.
4. End-to-End (E2E) Testing
Purpose: Verify that the entire application works from the user's perspective in a real browser.
An E2E test typically interacts with:
- Actual application pages.
- Browser navigation.
- User input.
- Backend APIs or a controlled test backend.
- Database or test data where appropriate.
Example: Complete shopping journey.
Using Playwright
import { test, expect } from '@playwright/test';
test('user can search and add a product to cart', async ({ page }) => {
await page.goto('http://localhost:5173');
await page.getByRole('textbox', {
name: /search products/i
}).fill('Laptop');
await page.getByText('Laptop').click();
await page.getByRole('button', {
name: /add to cart/i
}).click();
await expect(
page.getByText('Added to cart')
).toBeVisible();
await page.getByRole('link', {
name: /cart/i
}).click();
await expect(
page.getByText('Laptop')
).toBeVisible();
});
What does this test verify?
- The application loads.
- The search functionality works.
- Product selection works.
- Add-to-cart functionality works.
- Navigation works.
- The cart displays the selected product.
Unlike a typical React Testing Library test, this test runs through a browser and exercises the application as a user would.
Common E2E testing tools include:
- Playwright.
- Cypress.
5. Current React Testing Recommendations
The following recommendations reflect current Testing Library guidance and common React testing practices.
5.1 Prefer React Testing Library
Use React Testing Library (@testing-library/react) for testing React components.
It encourages testing the rendered DOM and user-visible behaviour instead of component internals.
Installation:
npm install -D @testing-library/react @testing-library/dom
Avoid relying on:
- Internal component state.
- Private component methods.
- Implementation-specific details.
- Component instance inspection.
The objective is to test what the user experiences, not how the component implements it.
5.2 Prefer userEvent Over fireEvent
Use @testing-library/user-event for normal user interactions.
Installation:
npm install -D @testing-library/user-event
Recommended:
const user = userEvent.setup();
await user.click(
screen.getByRole('button', { name: /submit/i })
);
Difference:
| userEvent | fireEvent |
|---|---|
| Simulates user interactions. | Dispatches individual DOM events. |
| Handles multiple events involved in an interaction. | Triggers the specified event. |
| Checks whether elements can be interacted with. | Does not simulate the complete interaction. |
| Preferred for normal user interactions. | Useful for specific low-level events. |
Use fireEvent when you need to trigger a particular event that userEvent does not support.
5.3 Prefer Accessible Queries
Testing Library recommends choosing queries in this general order:
getByRole()– preferred for most elements.getByLabelText()– particularly useful for form fields.getByPlaceholderText()– when appropriate.getByText()– for visible text.getByTestId()– as a last resort.
Example:
// Preferred
screen.getByRole('button', { name: /login/i });
// Good for form fields
screen.getByLabelText(/email address/i);
// Use when semantic queries are unsuitable
screen.getByTestId('custom-widget');
Why prefer getByRole()?
It encourages accessible UI design and makes tests closer to how users and assistive technologies find elements.
5.4 Use the Correct Asynchronous Queries
Testing Library provides three main query families.
| Query | Purpose |
|---|---|
| getBy | Element should already exist. |
| queryBy | Check whether an element exists or does not exist. |
| findBy | Element may appear asynchronously. |
Example:
// Element should exist immediately
expect(
screen.getByText('Welcome')
).toBeInTheDocument();
// Element should not exist
expect(
screen.queryByText('Loading...')
).not.toBeInTheDocument();
// Element appears after an API response
expect(
await screen.findByText('John')
).toBeInTheDocument();
Use waitFor() when you need to wait for an asynchronous assertion that is not conveniently expressed through findBy.
await waitFor(() => {
expect(mockFunction).toHaveBeenCalled();
});
Do not put user interactions inside a waitFor() callback. It may execute more than once.
5.5 Use MSW for API Mocking
Use Mock Service Worker (MSW) to intercept network requests and return controlled responses.
Instead of mocking internal API functions everywhere, MSW allows tests to exercise the application's actual request-handling code.
Example using MSW v2:
import { http, HttpResponse } from 'msw';
import { setupServer } from 'msw/node';
export const server = setupServer(
http.get('/api/users', () => {
return HttpResponse.json([
{ id: 1, name: 'John' }
]);
})
);
Typical test setup:
beforeAll(() => server.listen());
afterEach(() => server.resetHandlers());
afterAll(() => server.close());
Test different API conditions:
- Successful response.
- Empty response.
- Server error.
- Network failure.
- Slow response.
5.6 Use Vitest or Jest as the Test Runner
Both are valid choices.
| Vitest | Jest |
|---|---|
| Designed to work closely with Vite. | Established JavaScript testing framework. |
| Supports modern JavaScript tooling. | Has a broad ecosystem. |
| Provides mocking and coverage features. | Provides mocking and coverage features. |
| Suitable for many modern Vite React applications. | Suitable for many React applications. |
For a new React application using Vite, Vitest is a practical choice.
Installation:
npm install -D vitest jsdom
For browser-based testing, Vitest also provides Browser Mode. Its browser-specific interaction APIs differ from the usual JSDOM and user-event setup, so follow the appropriate documentation for the chosen environment.
5.7 Test Behaviour, Not Implementation
Bad example:
expect(component.state.search).toBe('Laptop');
This depends on internal implementation.
Better example:
expect(
screen.getByText('Laptop')
).toBeInTheDocument();
The second test verifies the visible result, regardless of how the component manages its state.
5.8 Avoid Excessive Snapshot Testing
Snapshots can be useful for stable, focused output, but they should not replace meaningful behavioural assertions.
Prefer:
expect(
screen.getByRole('button', { name: /save/i })
).toBeDisabled();
Over relying on a large snapshot to detect every UI change.
5.9 Test Important User States
For every important feature, consider:
- Initial state.
- Loading state.
- Success state.
- Empty state.
- Error state.
- Disabled state.
- Validation state.
- Retry or recovery behaviour.
For example, a login form should not only test successful login. It should also test invalid credentials, missing fields, loading behaviour and server errors.
5.10 Use Realistic Test Environments
JSDOM is useful for many component and integration tests, but it is not a complete browser.
Use browser-based E2E tests for behaviour involving:
- Actual browser navigation.
- Browser storage.
- Responsive layouts.
- Real rendering and browser APIs.
- Critical end-to-end workflows.
React also provides act() for ensuring updates are processed before assertions when working directly with lower-level React testing APIs. Most React Testing Library usage handles this automatically.
6. Recommended Testing Tools for React
| Tool | Primary Responsibility |
|---|---|
| React Testing Library | Render and test React components. |
| user-event | Simulate user interactions. |
| Vitest | Run unit and integration tests. |
| Jest | Alternative test runner. |
| MSW | Mock API/network requests. |
| jest-dom | Additional DOM assertions. |
| Playwright | Browser-based E2E testing. |
| Cypress | E2E and component testing. |
A practical modern combination for a Vite React application:
- Unit and Integration Testing: Vitest + React Testing Library + user-event + MSW.
- End-to-End Testing: Playwright.
7. How the Three Testing Levels Work Together
Consider a login feature.
1. Unit Test
Test validation logic
Verify that an email validator accepts valid email formats and rejects invalid ones.
2. Integration Test
Test the login form
Verify that form inputs, validation, API requests, loading indicators and error messages work together.
3. E2E Test
Test the complete login journey
Open the application, enter credentials, submit the form and verify that the user reaches the dashboard.
8. How Much Testing Should a React Application Have?
There is no mandatory percentage or universal ratio. A useful strategy is to invest most of your testing effort in unit and integration tests, while maintaining a smaller, carefully selected set of E2E tests.
| Level | Suggested Focus | Execution |
|---|---|---|
| Unit | Utilities, calculations, validation and isolated logic. | Frequently. |
| Integration | Important components, forms, API workflows and state interactions. | Frequently. |
| E2E | Critical business journeys. | In CI/CD and before releases. |
Do not measure testing quality only by code coverage. A test that executes code without verifying meaningful behaviour provides limited confidence.
9. Example Project Folder Structure
src/
│
├── components/
│ ├── Button.jsx
│ ├── Button.test.jsx
│ ├── LoginForm.jsx
│ └── LoginForm.test.jsx
│
├── pages/
│ ├── LoginPage.jsx
│ └── LoginPage.test.jsx
│
├── services/
│ ├── authService.js
│ └── authService.test.js
│
├── utils/
│ ├── calculateTotal.js
│ └── calculateTotal.test.js
│
└── test/
├── setup.js
└── server.js
e2e/
├── login.spec.js
├── checkout.spec.js
└── search.spec.js
10. Common Testing Mistakes to Avoid
- Testing internal React state instead of visible behaviour.
- Using
data-testidfor every element. - Using
fireEventas the default for all user interactions. - Making real API calls in ordinary component tests.
- Testing only successful scenarios.
- Writing too many fragile snapshots.
- Forgetting to await asynchronous interactions.
- Writing E2E tests for every small component.
- Making tests dependent on one another.
- Mocking so much that the test no longer verifies meaningful application behaviour.
11. Interview Questions and Answers
Q1. What is the difference between unit and integration testing in React?
Unit testing verifies an individual function, component or logic unit in isolation. Integration testing verifies whether multiple components, hooks, services or application features work correctly together.
Q2. Is React Testing Library used for unit or integration testing?
It can be used for both. Testing Library provides tools for rendering and interacting with React components. The classification depends on what the test verifies.
Q3. What is the difference between React Testing Library and Playwright?
React Testing Library is primarily used to test React components through their rendered DOM. Playwright automates real browsers to test complete application workflows.
Q4. Why should we prefer userEvent over fireEvent?
userEvent simulates more complete user interactions, whereas fireEvent dispatches individual DOM events.
Q5. Why do we use MSW?
MSW intercepts network requests and returns controlled responses, allowing tests to verify API-related application behaviour without depending on real backend services.
Q6. Should every React component have a unit test?
No. Focus on meaningful behaviour and important functionality. Testing every trivial component separately can create unnecessary maintenance overhead.
Q7. Can React Testing Library replace E2E testing?
No. It is excellent for component and integration testing, but it does not replace complete browser-based user journey testing.
Q8. What is the testing pyramid?
It is a testing strategy that encourages many fast, focused unit tests, a substantial number of integration tests and fewer E2E tests covering critical workflows.
12. Final Recommendations
For a modern React project:
- Use Vitest for running unit and integration tests in a Vite project.
- Use React Testing Library for component and integration testing.
- Use user-event for normal user interactions.
- Prefer
getByRole()and accessible queries. - Use MSW for API request mocking.
- Use Playwright for critical end-to-end workflows.
- Test loading, success, empty and error states.
- Focus on user-visible behaviour rather than implementation details.
Most important distinction:
- Unit tests check individual pieces.
- Integration tests check how pieces work together.
- E2E tests check whether the complete application works for the user.
Official Documentation
| Common React Testing Mistakes :👈 | 👉:React-QA-1 |
Comments and Discussion