Let's dive into how you can mimic the fetch
function in Chrome's Developer Tools using Playwright's API request context.
First, import the necessary modules from Playwright:
import { test } from '@playwright/test';
Now, within your test function, use the page.route
method to intercept the desired API endpoint. Let's say you want to mimic a fetch
call to an endpoint that returns JSON data:
test('mimic fetch using page.route', async ({ page }) => {
await page.route('**/api/endpoint', async (route) => {
const response = {
status: 200,
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ key: 'value' }),
};
await route.fulfill(response);
});
const result = await page.evaluate(() => {
return fetch('/api/endpoint').then((response) => response.json());
});
});
In this example, page.route
with a wildcard pattern (**/api/endpoint
) matches any requests made to /api/endpoint
. Inside the route handler function, we create a custom response object with the desired status code, headers, and body. Then we fulfill the route with this custom response.
After setting up the route interception, we perform our "fetch" operation using page.evaluate
. Here, we use JavaScript's native fetch
function inside an evaluation context on the page. The response is then processed by calling .json()
to parse the JSON data.
You can now add assertions or perform further actions based on the result of the "fetch" operation. By using page.route
and customizing the response, you can mimic the behavior of a fetch
call in Chrome's Developer Tools using Playwright's API request context.
If you still have questions, please ask a question and I will try to answer it.
Rayrun is a community for QA engineers. I am constantly looking for new ways to add value to people learning Playwright and other browser automation frameworks. If you have feedback, email [email protected].