Mocking Network Requests
Mastering network request control is essential for effective end-to-end testing in React applications. With Playwright, you can intercept and mock API requests, allowing you to test how your app behaves under various network conditions. To intercept and mock API requests, you use Playwright's network interception API. This involves listening for specific network calls and then responding with custom data, rather than allowing the request to reach the real backend.
Start by using the page.route method, which lets you define a handler for requests matching a given URL pattern. Inside this handler, you can decide whether to let the request continue to the server, fulfill it with mock data, or abort it entirely. For example, you might want to test how your React component renders when the API returns a specific user profile.
Verifying network calls is another important aspect of robust testing. After intercepting requests, you can make assertions about which endpoints were called, with what data, and how your application responds to different scenarios. Playwright allows you to wait for specific requests using page.waitForRequest or page.waitForResponse, ensuring your test logic aligns with real network activity.
Simulating error responses is equally valuable. You can use the same interception techniques to return error codes like 404 or 500, or even simulate a network timeout. This helps you confirm that your React app handles failures gracefully, displaying the correct error messages or fallback UI. By controlling and asserting network activity in your Playwright tests, you gain confidence that your application behaves correctly across both success and failure scenarios.
src/App.jsx
import { useEffect, useState } from "react";
export default function App() {
const [user, setUser] = useState(null);
const [error, setError] = useState(null);
useEffect(() => {
fetch("/api/user")
.then((res) => {
if (!res.ok) throw new Error("Request failed");
return res.json();
})
.then(setUser)
.catch(() => setError("Failed to load user"));
}, []);
if (error) {
return <p role="alert">{error}</p>;
}
if (!user) {
return <p>Loading...</p>;
}
return <h1>Welcome, {user.name}</h1>;
}
e2e/tests/mock-success.spec.ts
import { test, expect } from "@playwright/test";
test("renders user from mocked API response", async ({ page }) => {
await page.route("/api/user", async (route) => {
await route.fulfill({
status: 200,
contentType: "application/json",
body: JSON.stringify({ name: "Alice" }),
});
});
await page.goto("/");
await expect(
page.getByRole("heading", { name: "Welcome, Alice" })
).toBeVisible();
});
Дякуємо за ваш відгук!
Запитати АІ
Запитати АІ
Запитайте про що завгодно або спробуйте одне із запропонованих запитань, щоб почати наш чат
Чудово!
Completion показник покращився до 6.67
Mocking Network Requests
Свайпніть щоб показати меню
Mastering network request control is essential for effective end-to-end testing in React applications. With Playwright, you can intercept and mock API requests, allowing you to test how your app behaves under various network conditions. To intercept and mock API requests, you use Playwright's network interception API. This involves listening for specific network calls and then responding with custom data, rather than allowing the request to reach the real backend.
Start by using the page.route method, which lets you define a handler for requests matching a given URL pattern. Inside this handler, you can decide whether to let the request continue to the server, fulfill it with mock data, or abort it entirely. For example, you might want to test how your React component renders when the API returns a specific user profile.
Verifying network calls is another important aspect of robust testing. After intercepting requests, you can make assertions about which endpoints were called, with what data, and how your application responds to different scenarios. Playwright allows you to wait for specific requests using page.waitForRequest or page.waitForResponse, ensuring your test logic aligns with real network activity.
Simulating error responses is equally valuable. You can use the same interception techniques to return error codes like 404 or 500, or even simulate a network timeout. This helps you confirm that your React app handles failures gracefully, displaying the correct error messages or fallback UI. By controlling and asserting network activity in your Playwright tests, you gain confidence that your application behaves correctly across both success and failure scenarios.
src/App.jsx
import { useEffect, useState } from "react";
export default function App() {
const [user, setUser] = useState(null);
const [error, setError] = useState(null);
useEffect(() => {
fetch("/api/user")
.then((res) => {
if (!res.ok) throw new Error("Request failed");
return res.json();
})
.then(setUser)
.catch(() => setError("Failed to load user"));
}, []);
if (error) {
return <p role="alert">{error}</p>;
}
if (!user) {
return <p>Loading...</p>;
}
return <h1>Welcome, {user.name}</h1>;
}
e2e/tests/mock-success.spec.ts
import { test, expect } from "@playwright/test";
test("renders user from mocked API response", async ({ page }) => {
await page.route("/api/user", async (route) => {
await route.fulfill({
status: 200,
contentType: "application/json",
body: JSON.stringify({ name: "Alice" }),
});
});
await page.goto("/");
await expect(
page.getByRole("heading", { name: "Welcome, Alice" })
).toBeVisible();
});
Дякуємо за ваш відгук!