| How to Write Integration Tests for React Pages :👈 | 👉:React Testing, Unit test, Libraries |
Common React Testing Mistakes |
Common React Testing Mistakes and How to Avoid Them
1. Testing Implementation Details Instead of User Behavior
One of the most common mistakes is testing internal component details instead of verifying what users actually experience.
Incorrect approach:
// Checking internal state directly
expect(component.state.count).toBe(1);
This approach makes tests dependent on implementation details. If the component is refactored, the test may break even when the UI behaves correctly.
Correct approach:
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
function Counter() {
const [count, setCount] = React.useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>
Increment
</button>
</div>
);
}
it("should increment the counter", async () => {
const user = userEvent.setup();
render(<Counter />);
await user.click(
screen.getByRole("button", { name: "Increment" })
);
expect(screen.getByText("Count: 1")).toBeInTheDocument();
});
Why is this better? It verifies the actual behavior visible to users without depending on internal state.
2. Using getBy Instead of findBy for Asynchronous Elements
Another common mistake is using getBy queries for elements that appear after an asynchronous operation.
Incorrect:
expect(
screen.getByText("John")
).toBeInTheDocument();
If John appears only after an API request completes, getByText may fail because the element is not available immediately.
Correct:
expect(
await screen.findByText("John")
).toBeInTheDocument();
Remember:
- getBy: Finds an element immediately.
- queryBy: Checks whether an element exists or is absent.
- findBy: Waits for an element to appear asynchronously.
3. Using fireEvent Instead of userEvent for Everything
React Testing Library provides both fireEvent and userEvent.
A common mistake is using fireEvent for every user interaction.
Example using fireEvent:
import { fireEvent } from "@testing-library/react";
fireEvent.click(
screen.getByRole("button")
);
Recommended approach:
import userEvent from "@testing-library/user-event";
const user = userEvent.setup();
await user.click(
screen.getByRole("button")
);
Difference:
| fireEvent | userEvent |
|---|---|
| Dispatches a specific DOM event. | Simulates more realistic user interactions. |
| Useful for low-level event testing. | Recommended for most normal user interactions. |
| Does not automatically reproduce the complete interaction sequence. | Models interactions such as typing, clicking and keyboard navigation more closely. |
4. Not Testing Loading, Error and Empty States
Developers sometimes test only successful API responses and ignore other possible states.
Consider a component that fetches users from an API.
It should handle:
- Loading state
- Successful response
- Empty response
- HTTP error
- Network failure
Example:
it("should display loading message", () => {
expect(screen.getByRole("status"))
.toHaveTextContent("Loading...");
});
it("should display users after loading", async () => {
expect(
await screen.findByText("John")
).toBeInTheDocument();
});
it("should display an error message", async () => {
expect(
await screen.findByRole("alert")
).toHaveTextContent("Something went wrong");
});
Best practice: Test the complete data-fetching lifecycle, not just the successful response.
5. Making Real API Calls During Tests
Another mistake is allowing tests to call actual production or external APIs.
This creates several problems:
- Tests depend on network availability.
- Tests may become slow.
- External services may be unavailable.
- API data can change unexpectedly.
- Tests become difficult to reproduce.
Recommended approach: Use MSW.
import { http, HttpResponse } from "msw";
export const handlers = [
http.get("/api/users", () => {
return HttpResponse.json([
{ id: 1, name: "John" },
{ id: 2, name: "David" }
]);
})
];
MSW intercepts network requests and returns controlled responses.
This makes tests predictable without depending on real external services.
6. Forgetting to Wrap Components with Providers
Components that use Context, React Router or other Providers may fail when rendered without their required dependencies.
Incorrect:
render(<Dashboard />);
If Dashboard uses authentication Context and React Router, this may cause errors.
Correct:
render(
<MemoryRouter>
<AuthProvider>
<Dashboard />
</AuthProvider>
</MemoryRouter>
);
Best practice: Create a reusable custom render function when multiple tests need the same Providers.
7. Testing Too Many Implementation Details
Tests should not depend unnecessarily on internal component structure.
Incorrect:
expect(container.querySelector(".submit-btn"))
.toBeInTheDocument();
This relies on a CSS class that may change during refactoring.
Correct:
expect(
screen.getByRole("button", { name: "Submit" })
).toBeInTheDocument();
Using accessible roles and labels makes tests more meaningful and less dependent on styling.
8. Using data-testid Everywhere
data-testid is useful when an element cannot be identified reliably through accessible roles, labels or text.
However, using it everywhere is a mistake.
Less preferred:
<button data-testid="login-button">
Login
</button>
screen.getByTestId("login-button");
Preferred:
<button>Login</button>
screen.getByRole("button", { name: "Login" });
Query priority:
- getByRole()
- getByLabelText()
- getByPlaceholderText()
- getByText()
- getByDisplayValue()
- getByTestId()
9. Not Awaiting userEvent Operations
Modern userEvent interactions return Promises. Forgetting await can cause tests to execute assertions before the interaction has completed.
Incorrect:
user.click(
screen.getByRole("button")
);
expect(screen.getByText("Success"))
.toBeInTheDocument();
Correct:
const user = userEvent.setup();
await user.click(
screen.getByRole("button")
);
expect(
screen.getByText("Success")
).toBeInTheDocument();
Best practice: Await userEvent interactions before checking their results.
10. Using waitFor Incorrectly
waitFor is useful for waiting until an assertion succeeds. However, developers sometimes use it unnecessarily or place multiple unrelated operations inside it.
Incorrect:
await waitFor(async () => {
await user.click(
screen.getByRole("button")
);
expect(screen.getByText("Success"))
.toBeInTheDocument();
});
The interaction is repeated whenever the callback is retried, which can cause unexpected behavior.
Correct:
await user.click(
screen.getByRole("button")
);
await waitFor(() => {
expect(
screen.getByText("Success")
).toBeInTheDocument();
});
For an element that appears asynchronously, findBy is usually simpler:
expect(
await screen.findByText("Success")
).toBeInTheDocument();
11. Not Cleaning Up Mocks and Global State
Mocks can affect other tests if they are not properly restored.
For example, using vi.stubGlobal() to mock fetch may leave the mocked fetch function available to subsequent tests.
Recommended approach:
import { afterEach, vi } from "vitest";
afterEach(() => {
vi.unstubAllGlobals();
vi.restoreAllMocks();
});
Use the appropriate cleanup method for the type of mock being used. Also reset MSW handlers after each test.
Why is this important?
- Prevents tests from affecting one another.
- Reduces unpredictable failures.
- Makes test results more reliable.
12. Writing Tests That Depend on Execution Order
Each test should be independent. One test should not require another test to execute first.
Incorrect approach:
- Test 1 creates a user.
- Test 2 assumes that user exists.
- Test 3 updates the same user.
If Test 1 fails, the other tests may also fail.
Correct approach:
Each test should prepare its own required data and mock responses.
it("should display a user", () => {
const user = {
id: 1,
name: "John"
};
render(<UserProfile user={user} />);
expect(
screen.getByText("John")
).toBeInTheDocument();
});
13. Writing Very Large Tests
Another mistake is writing one test that verifies too many unrelated behaviors.
For example, a single test may:
- Render a login page.
- Validate form fields.
- Submit credentials.
- Handle an API error.
- Retry the request.
- Navigate to the dashboard.
When the test fails, identifying the exact problem becomes difficult.
Better approach: Divide the scenarios into focused tests.
describe("LoginPage", () => {
it("should render the login form", () => {
// Rendering test
});
it("should validate required fields", () => {
// Validation test
});
it("should display API errors", () => {
// Error handling test
});
it("should navigate after successful login", () => {
// Successful workflow test
});
});
Each test should have a clear purpose. However, do not split a meaningful user workflow into so many tiny tests that integration behavior is lost.
14. Testing Only the Happy Path
The happy path is the scenario in which everything works as expected.
For example:
- Valid input is entered.
- API request succeeds.
- Data is displayed.
But real applications also experience failures.
Test scenarios such as:
- Invalid user input.
- Missing required fields.
- API request failure.
- Network disconnection.
- Empty API response.
- Unauthorized access.
- Repeated button clicks.
Testing both successful and unsuccessful scenarios provides better coverage of application behavior.
15. Not Testing Accessibility
Testing only whether elements are visible is not sufficient. Components should also be accessible to users who rely on assistive technologies.
For example, form fields should have accessible labels.
Incorrect:
<input type="email" placeholder="Enter email" />
Better:
<label htmlFor="email">Email</label>
<input
id="email"
type="email"
/>
Now the test can identify the input through its label:
screen.getByLabelText("Email");
Also consider testing:
- Accessible button names.
- Keyboard navigation.
- Focus behavior.
- Appropriate error announcements.
- Accessible dialog behavior.
16. Not Testing React Effects and Cleanup
Components may use useEffect() to subscribe to events, start timers or fetch data.
Forgetting to test cleanup behavior can allow subscriptions or timers to remain active after a component is removed.
Example component:
import { useEffect, useState } from "react";
function WindowWidth() {
const [width, setWidth] = useState(window.innerWidth);
useEffect(() => {
function handleResize() {
setWidth(window.innerWidth);
}
window.addEventListener("resize", handleResize);
return () => {
window.removeEventListener("resize", handleResize);
};
}, []);
return <p>Width: {width}</p>;
}
Test that the event listener is removed when the component unmounts.
import { render } from "@testing-library/react";
import { expect, it, vi } from "vitest";
import WindowWidth from "./WindowWidth";
it("should remove resize listener on unmount", () => {
const removeSpy = vi.spyOn(
window,
"removeEventListener"
);
const { unmount } = render(<WindowWidth />);
unmount();
expect(removeSpy).toHaveBeenCalledWith(
"resize",
expect.any(Function)
);
removeSpy.mockRestore();
});
17. Not Understanding React StrictMode Behavior
In development, React StrictMode may run certain rendering and Effect setup/cleanup sequences an additional time to help identify bugs.
This can surprise developers when they see API calls or Effect callbacks execute more than once during development tests.
Common mistake: Assuming that every Effect must run exactly once.
Better approach:
- Understand StrictMode behavior.
- Write Effects that correctly handle setup and cleanup.
- Avoid relying on exact Effect invocation counts unless that is specifically what the test needs to verify.
- Test the user-visible result rather than assuming development Effect execution matches production.
18. Not Testing Error Boundaries
Error Boundaries catch rendering errors in their descendant component trees and display fallback UI.
Developers sometimes test normal rendering but forget to test the fallback behavior.
Example:
class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = {
hasError: false
};
}
static getDerivedStateFromError() {
return {
hasError: true
};
}
render() {
if (this.state.hasError) {
return <p>Something went wrong</p>;
}
return this.props.children;
}
}
Test the fallback UI by rendering a child component that throws during rendering.
function BrokenComponent() {
throw new Error("Rendering failed");
}
it("should display fallback UI when a child throws", () => {
const consoleSpy = vi
.spyOn(console, "error")
.mockImplementation(() => {});
render(
<ErrorBoundary>
<BrokenComponent />
</ErrorBoundary>
);
expect(
screen.getByText("Something went wrong")
).toBeInTheDocument();
consoleSpy.mockRestore();
});
In production-quality tests, restore console spies using afterEach or try/finally so cleanup also happens when an assertion fails.
19. Ignoring Test Coverage Quality
High code coverage does not automatically mean good tests.
For example, a test may execute a function without checking whether it produces the correct result.
Weak test:
it("should call calculateTotal", () => {
calculateTotal(100, 10);
});
Better test:
it("should calculate total including tax", () => {
const result = calculateTotal(100, 10);
expect(result).toBe(110);
});
Focus on meaningful assertions and important application behavior rather than trying to achieve 100% coverage at any cost.
20. Common React Testing Mistakes: Quick Comparison
| Mistake | Better Practice |
|---|---|
| Testing internal state | Test visible UI behavior. |
| Using getBy for asynchronous content | Use findBy. |
| Using fireEvent for everything | Prefer userEvent for normal interactions. |
| Calling real APIs | Use MSW or controlled mocks. |
| Ignoring loading and error states | Test the complete data lifecycle. |
| Forgetting Providers | Wrap components with required Providers. |
| Using data-testid everywhere | Prefer accessible queries. |
| Not awaiting userEvent | Use await with interactions. |
| Using waitFor unnecessarily | Prefer findBy for asynchronous elements. |
| Not restoring mocks | Clean up mocks after tests. |
| Dependent tests | Make each test independent. |
| Testing only happy paths | Include failure scenarios. |
| Testing only code execution | Verify meaningful outcomes. |
21. Recommended React Testing Checklist
Before completing a React test suite, verify the following:
- Page and component rendering tests are available.
- User interactions are tested.
- Form validation is tested.
- Loading and success states are tested.
- Error and empty states are tested.
- API requests are mocked appropriately.
- Context Providers and routing are configured correctly.
- Navigation behavior is tested.
- Accessibility queries are preferred.
- Asynchronous operations are awaited.
- Mocks and global state are cleaned up.
- Tests can run independently.
- Important application workflows have integration tests.
22. Interview Questions and Answers
Q1. What is the most common mistake in React testing?
Testing implementation details instead of user-visible behavior. Tests should focus on what users see and do.
Q2. Why should we prefer userEvent over fireEvent?
userEvent simulates more realistic user interactions, including the sequence of events involved in actions such as typing and clicking.
Q3. What is the difference between getBy and findBy?
getBy searches immediately, whereas findBy waits for an element to appear asynchronously.
Q4. Why should we avoid real API calls in tests?
Real API calls make tests dependent on network availability and external services. Mocking makes tests faster, predictable and repeatable.
Q5. Why should tests be independent?
Independent tests can run in any order and do not fail because another test changed shared state.
Q6. Is 100% test coverage necessary?
No. Coverage is a useful measurement, but meaningful assertions and testing important application behavior are more valuable than pursuing a percentage alone.
Q7. Why should we avoid excessive data-testid usage?
It can make tests dependent on implementation-specific attributes. Accessible queries such as getByRole and getByLabelText are generally more meaningful.
Q8. What is the purpose of MSW?
MSW intercepts network requests and provides controlled responses, allowing API behavior to be tested without depending on real external services.
Q9. How does React StrictMode affect tests?
In development, StrictMode may repeat certain rendering and Effect setup/cleanup sequences to identify potential problems. Tests should not assume Effects always execute exactly once.
Q10. How do you prevent flaky React tests?
Use controlled API responses, await asynchronous operations, avoid arbitrary delays, clean up mocks, and ensure tests are independent.
23. Key Takeaway
Good React tests should be reliable, readable, maintainable and focused on actual application behavior.
The most important practices are:
- Test user-visible behavior instead of implementation details.
- Use React Testing Library with userEvent.
- Use findBy and waitFor appropriately.
- Mock external API requests with MSW.
- Test loading, success, error and empty states.
- Keep tests independent and clean up mocks.
- Test accessibility and important user workflows.
- Write meaningful assertions instead of focusing only on coverage.
Remember: A good test should give confidence that the application works correctly from the user's perspective, even when its internal implementation changes.
| How to Write Integration Tests for React Pages :👈 | 👉:React Testing, Unit test, Libraries |
Comments and Discussion