| How to Test Components with Asynchronous Data :👈 | 👉:Common React Testing Mistakes |
How to Write Integration Tests for React Pages |
How to Write Integration Tests for React Pages
1. What Are Integration Tests in React?
Integration tests verify whether multiple components, hooks, services, Context Providers, and other application features work together correctly.
Consider an e-commerce application with a Product Listing page.
When a user opens the page:
- The page loads.
- The application fetches products from an API.
- The product list component displays the products.
- The user selects a product.
- The product details page opens.
- The user adds the product to the cart.
- The cart displays the updated quantity.
An integration test can verify this complete user journey across multiple application parts.
2. Unit Testing vs Integration Testing vs E2E Testing
| Testing Type | What It Tests | Example |
|---|---|---|
| Unit Testing | Individual functions or components. | Testing a button click handler. |
| Integration Testing | Multiple components and application features working together. | Testing login form submission and navigation. |
| End-to-End Testing | Complete application workflows in a browser. | Testing login, shopping cart and checkout in a real browser. |
Important: React Testing Library is commonly used for component and integration tests. Playwright and Cypress are commonly used for browser-based end-to-end tests.
3. Tools Required for Integration Testing
| Tool | Purpose |
|---|---|
| React Testing Library | Renders React pages and tests user-visible behavior. |
| Vitest | Runs tests and provides assertions and mocking. |
| user-event | Simulates typing, clicking and other user interactions. |
| MSW | Mocks API requests at the network boundary. |
| React Router | Provides routing for page-level integration tests. |
| jest-dom | Provides additional DOM assertions. |
4. Install Testing Dependencies
For a React application using Vite, install the following packages:
npm install -D vitest jsdom
npm install -D @testing-library/react
npm install -D @testing-library/jest-dom
npm install -D @testing-library/user-event
npm install -D msw
If the application uses React Router, install it if it is not already available:
npm install react-router-dom
Configure Vitest
vite.config.js
import { defineConfig } from "vitest/config";
import react from "@vitejs/plugin-react";
export default defineConfig({
plugins: [react()],
test: {
environment: "jsdom",
setupFiles: "./src/setupTests.js",
globals: true
}
});
Configure the test setup file
src/setupTests.js
import "@testing-library/jest-dom/vitest";
Add a test script
In package.json:
{
"scripts": {
"test": "vitest",
"test:run": "vitest run"
}
}
5. Example: Login Page Integration Testing
Let's create a practical example where a login page integrates several application features.
Our login page will contain:
- Login form
- Email and password inputs
- Form validation
- Authentication API request
- Loading indicator
- Error message
- Navigation to the dashboard after successful login
Step 1: Create an Authentication Service
src/services/authService.js
export async function login(credentials) {
const response = await fetch("/api/login", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(credentials)
});
if (!response.ok) {
throw new Error("Invalid email or password");
}
return response.json();
}
This service sends the login credentials to the API and returns the authentication response.
Step 2: Create the Login Page
src/pages/LoginPage.jsx
import { useState } from "react";
import { useNavigate } from "react-router-dom";
import { login } from "../services/authService";
function LoginPage() {
const navigate = useNavigate();
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [error, setError] = useState("");
const [loading, setLoading] = useState(false);
async function handleSubmit(event) {
event.preventDefault();
setError("");
setLoading(true);
try {
const result = await login({
email,
password
});
if (result.token) {
navigate("/dashboard");
}
} catch (err) {
setError(err.message);
} finally {
setLoading(false);
}
}
return (
<form onSubmit={handleSubmit}>
<h1>Login</h1>
<label htmlFor="email">Email</label>
<input
id="email"
type="email"
value={email}
onChange={event => setEmail(event.target.value)}
required
/>
<label htmlFor="password">Password</label>
<input
id="password"
type="password"
value={password}
onChange={event => setPassword(event.target.value)}
required
/>
<button type="submit" disabled={loading}>
{loading ? "Logging in..." : "Login"}
</button>
{error && (
<p role="alert">{error}</p>
)}
</form>
);
}
export default LoginPage;
Step 3: Create the Dashboard Page
src/pages/DashboardPage.jsx
function DashboardPage() {
return (
<div>
<h1>Dashboard</h1>
<p>Welcome to your dashboard</p>
</div>
);
}
export default DashboardPage;
Step 4: Configure Application Routes
src/App.jsx
import { BrowserRouter, Routes, Route } from "react-router-dom";
import LoginPage from "./pages/LoginPage";
import DashboardPage from "./pages/DashboardPage";
function App() {
return (
<BrowserRouter>
<Routes>
<Route path="/" element={<LoginPage />} />
<Route
path="/dashboard"
element={<DashboardPage />}
/>
</Routes>
</BrowserRouter>
);
}
export default App;
6. Write Integration Tests for the Login Page
We will use React Testing Library and React Router's MemoryRouter to test the complete page without opening a real browser.
Test 1: Verify Login Page Rendering
First, verify that all important form elements are displayed.
src/pages/LoginPage.test.jsx
import { render, screen } from "@testing-library/react";
import { MemoryRouter } from "react-router-dom";
import { expect, it } from "vitest";
import LoginPage from "./LoginPage";
it("should display the login form", () => {
render(
<MemoryRouter>
<LoginPage />
</MemoryRouter>
);
expect(
screen.getByRole("heading", { name: "Login" })
).toBeInTheDocument();
expect(
screen.getByLabelText("Email")
).toBeInTheDocument();
expect(
screen.getByLabelText("Password")
).toBeInTheDocument();
expect(
screen.getByRole("button", { name: "Login" })
).toBeInTheDocument();
});
This verifies that the login page renders its expected UI.
Test 2: Verify Successful Login and Navigation
Now test the complete successful login workflow.
For this test, we will use MSW to intercept the API request.
src/mocks/handlers.js
import { http, HttpResponse } from "msw";
export const handlers = [
http.post("/api/login", async ({ request }) => {
const credentials = await request.json();
if (
credentials.email === "test@example.com" &&
credentials.password === "password123"
) {
return HttpResponse.json({
token: "mock-token",
user: {
name: "John"
}
});
}
return HttpResponse.json(
{ message: "Invalid credentials" },
{ status: 401 }
);
})
];
src/mocks/server.js
import { setupServer } from "msw/node";
import { handlers } from "./handlers";
export const server = setupServer(...handlers);
Update the test setup file to start and stop the MSW server.
src/setupTests.js
import "@testing-library/jest-dom/vitest";
import { beforeAll, afterAll, afterEach } from "vitest";
import { server } from "./mocks/server";
beforeAll(() => {
server.listen({
onUnhandledRequest: "error"
});
});
afterEach(() => {
server.resetHandlers();
});
afterAll(() => {
server.close();
});
LoginPage.test.jsx
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { MemoryRouter, Routes, Route } from "react-router-dom";
import { expect, it } from "vitest";
import LoginPage from "./LoginPage";
import DashboardPage from "./DashboardPage";
it("should login successfully and navigate to dashboard", async () => {
const user = userEvent.setup();
render(
<MemoryRouter initialEntries={["/"]}>
<Routes>
<Route path="/" element={<LoginPage />} />
<Route
path="/dashboard"
element={<DashboardPage />}
/>
</Routes>
</MemoryRouter>
);
await user.type(
screen.getByLabelText("Email"),
"test@example.com"
);
await user.type(
screen.getByLabelText("Password"),
"password123"
);
await user.click(
screen.getByRole("button", { name: "Login" })
);
expect(
await screen.findByRole("heading", {
name: "Dashboard"
})
).toBeInTheDocument();
expect(
screen.getByText("Welcome to your dashboard")
).toBeInTheDocument();
});
What does this integration test verify?
- The login page renders correctly.
- The user enters email and password.
- The user submits the form.
- The login service sends an API request.
- MSW returns a successful authentication response.
- The application navigates to the dashboard.
- The dashboard content is displayed.
This is an integration test because multiple application parts work together.
Test 3: Verify Invalid Login
Now test what happens when the API rejects the login request.
import { http, HttpResponse } from "msw";
import { server } from "../mocks/server";
it("should display an error for invalid login", async () => {
const user = userEvent.setup();
server.use(
http.post("/api/login", () => {
return HttpResponse.json(
{ message: "Invalid email or password" },
{ status: 401 }
);
})
);
render(
<MemoryRouter>
<LoginPage />
</MemoryRouter>
);
await user.type(
screen.getByLabelText("Email"),
"wrong@example.com"
);
await user.type(
screen.getByLabelText("Password"),
"wrongpassword"
);
await user.click(
screen.getByRole("button", { name: "Login" })
);
expect(
await screen.findByRole("alert")
).toHaveTextContent("Invalid email or password");
});
This verifies that the page handles API failures and displays an appropriate error message.
Test 4: Verify Loading State
We should also test what the user sees while the API request is pending.
it("should display loading state during login", async () => {
const user = userEvent.setup();
let resolveRequest;
const pendingResponse = new Promise(resolve => {
resolveRequest = resolve;
});
server.use(
http.post("/api/login", async () => {
await pendingResponse;
return HttpResponse.json({
token: "mock-token"
});
})
);
render(
<MemoryRouter>
<LoginPage />
</MemoryRouter>
);
await user.type(
screen.getByLabelText("Email"),
"test@example.com"
);
await user.type(
screen.getByLabelText("Password"),
"password123"
);
await user.click(
screen.getByRole("button", { name: "Login" })
);
expect(
screen.getByRole("button", {
name: "Logging in..."
})
).toBeDisabled();
resolveRequest();
expect(
await screen.findByText("Welcome to your dashboard")
).toBeInTheDocument();
});
This verifies that the loading indicator appears while the request is pending and that the successful workflow completes afterward.
7. Test Form Validation
Integration tests should also verify how the page behaves when the user submits incomplete information.
In our example, the email and password fields are required.
it("should prevent submission when required fields are empty", async () => {
const user = userEvent.setup();
render(
<MemoryRouter>
<LoginPage />
</MemoryRouter>
);
await user.click(
screen.getByRole("button", { name: "Login" })
);
expect(
screen.getByLabelText("Email")
).toBeInvalid();
expect(
screen.getByLabelText("Password")
).toBeInvalid();
});
This test checks the browser's native required-field validation. Since the form is invalid, its submit handler is not invoked.
8. Testing Pages That Use Context
Many React pages depend on Context Providers for authentication, theme settings, shopping cart information, or application state.
For integration testing, render the page inside the actual Provider when you want to verify how the Provider and page work together.
Example:
import { AuthProvider } from "../context/AuthContext";
import { MemoryRouter } from "react-router-dom";
import { render, screen } from "@testing-library/react";
it("should render the page with authentication context", () => {
render(
<MemoryRouter>
<AuthProvider>
<DashboardPage />
</AuthProvider>
</MemoryRouter>
);
expect(
screen.getByRole("heading", {
name: "Dashboard"
})
).toBeInTheDocument();
});
The example assumes AuthProvider is implemented to provide the required authentication state. If the page requires a logged-in user, configure the Provider with a suitable test state or use an appropriate test setup.
9. How to Structure Integration Tests for React Pages
A practical project structure could look like this:
src/
│
├── components/
│ ├── Header.jsx
│ ├── Button.jsx
│ └── Loading.jsx
│
├── pages/
│ ├── LoginPage.jsx
│ ├── LoginPage.test.jsx
│ ├── DashboardPage.jsx
│ └── DashboardPage.test.jsx
│
├── services/
│ └── authService.js
│
├── context/
│ └── AuthContext.jsx
│
├── mocks/
│ ├── handlers.js
│ └── server.js
│
├── test/
│ └── test-utils.jsx
│
└── setupTests.js
Keeping page tests close to their respective page components makes them easier to maintain.
10. What Should You Test in a React Page?
Use the following checklist when writing page-level integration tests.
- Page renders correctly.
- Important headings and content appear.
- Navigation works correctly.
- Forms accept user input.
- Form validation works.
- API requests are triggered correctly.
- Loading indicators appear and disappear.
- Successful API responses update the UI.
- Error messages appear when requests fail.
- Context values are consumed correctly.
- User interactions trigger the expected behavior.
- Empty states are displayed correctly.
- Retry actions work when supported.
11. Common Integration Testing Mistakes
1. Testing Every Child Component Separately
Integration tests should focus on how multiple components work together. Individual component behavior is better covered by unit or component tests.
2. Mocking Too Many Dependencies
If every component, hook, service, and Context Provider is mocked, the test may no longer verify meaningful integration.
Prefer using real application components and Providers while mocking external API boundaries.
3. Using Real API Services
Tests should not depend on production APIs because network availability and external data can make tests unpredictable.
Use MSW to return controlled API responses.
4. Testing Implementation Details
Avoid checking internal state variables or private component methods. Test what users see and do.
5. Not Testing Failure Scenarios
Successful workflows alone are not enough. Include loading, validation, API errors and empty states where applicable.
6. Using getBy for Asynchronous Content
Use findBy queries when content appears after an asynchronous operation.
expect(
await screen.findByText("Dashboard")
).toBeInTheDocument();
12. Best Practices
- Write integration tests around important user workflows.
- Use React Testing Library to test user-visible behavior.
- Use user-event for realistic interactions.
- Use MSW to mock API requests.
- Use MemoryRouter for page-level routing tests.
- Use actual Context Providers when testing integration with Context.
- Mock external services rather than internal application components unnecessarily.
- Test both successful and unsuccessful workflows.
- Keep tests independent and repeatable.
- Use meaningful test names that describe user behavior.
- Do not duplicate every unit test in the integration test suite.
13. Unit Tests vs Integration Tests: Practical Example
Consider a Login page with an EmailInput, PasswordInput, LoginButton, AuthService and Dashboard page.
| Test Type | What to Test |
|---|---|
| Unit Test | Verify that an email validation function rejects an invalid email. |
| Component Test | Verify that the LoginButton displays the correct label. |
| Integration Test | Enter credentials, submit the form, receive an API response and navigate to the dashboard. |
| E2E Test | Open the application in a browser and complete the login workflow against a test environment. |
14. Interview Questions and Answers
Q1. What is integration testing in React?
Integration testing verifies whether multiple React components and application features work together correctly, such as forms, Context Providers, API services and routing.
Q2. What is the difference between unit testing and integration testing?
Unit testing focuses on individual functions or components, whereas integration testing verifies interactions between multiple application parts.
Q3. Why is React Testing Library suitable for integration testing?
It encourages testing application behavior from the user's perspective rather than depending on internal component implementation.
Q4. How do you test React Router navigation?
Use MemoryRouter with Routes and Route to render the required pages and verify that the expected destination content appears after navigation.
Q5. How do you mock API requests in integration tests?
MSW can intercept network requests and return controlled responses without calling real external APIs.
Q6. Should we mock child components in integration tests?
Generally, keep important child components real so the test verifies their integration. Mock a child component only when it is expensive, external, or outside the behavior being tested.
Q7. How do you test a page that uses Context?
Wrap the page with the required Context Provider. Use the actual Provider when testing integration with its state and behavior.
Q8. What is MemoryRouter?
MemoryRouter is a React Router component that manages navigation using an in-memory history stack. It is useful for tests because it does not require a browser URL.
Q9. Should integration tests call real APIs?
Usually not. Mock external API responses with MSW to make tests predictable and independent of external services.
Q10. When should you use Playwright instead of React Testing Library?
Use Playwright when you need to test complete browser workflows, such as real navigation, browser behavior, page loading and interactions across multiple pages.
15. Key Takeaway
Integration tests verify that the different parts of a React application work together as expected.
A good page-level integration test should:
- Render the actual page.
- Provide the required Providers and Router.
- Mock external API requests using MSW.
- Simulate realistic user interactions.
- Verify the resulting UI and navigation.
- Cover success, loading, validation and error scenarios.
Remember: Test complete user workflows rather than only individual functions. This helps identify problems that occur when multiple parts of the React application interact.
| How to Test Components with Asynchronous Data :👈 | 👉:Common React Testing Mistakes |
Comments and Discussion