Rayrun

How can I intercept and modify network requests in Playwright?

Answer

Mimic Fetch Function Using Playwright's API Request Context

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.

References

Thank you!
Was this helpful?
Still have questions?

If you still have questions, please ask a question and I will try to answer it.

Related Discord Threads

Related Questions

TwitterGitHubLinkedIn
AboutQuestionsDiscord ForumBrowser ExtensionTagsQA Jobs

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].