Request Interception in Playwright: Mocking, Modifying, and Blocking Network Calls

Intercepting network requests is a powerful feature in Playwright that enables developers to monitor, modify, and mock HTTP requests and responses. This capability is invaluable for testing edge cases, enhancing test performance, and ensuring applications handle various scenarios gracefully.

Why Intercept Requests?

Intercepting requests allows you to:

  • Mock API Responses: Test how your application handles different API responses without relying on the actual backend.
  • Simulate Network Errors: Ensure your application behaves correctly during network failures.
  • Optimize Test Performance: By blocking unnecessary resources like images or ads, you can speed up test execution.

Setting Up Request Interception

In Playwright, you can intercept network requests using the page.route method. This method allows you to define a handler function that can modify or mock responses.

Example: Blocking Image Requests

To block all image requests and speed up your tests:

await page.route('**/*.{png,jpg,jpeg}', route => route. Abort());

This code intercepts requests for PNG, JPG, and JPEG images and aborts them, preventing the browser from downloading these resources. 

Example: Mocking API Responses

To mock an API response:

await page.route('https://api.example.com/data', route => {
  route.fulfill({
    status: 200,
    contentType: 'application/json',
    body: JSON.stringify({ key: 'mocked value' }),
  });
});

This intercepts requests to https://api.example.com/data and returns a mocked JSON response. 

Advanced Interception Techniques

Beyond basic interception, Playwright allows for more advanced scenarios:

Modifying Responses

You can fetch the original response, modify it, and then fulfill the request with the altered data:

await page.route('https://api.example.com/data', async route => {
  const response = await route.fetch();
  let body = await response.text();
  body = body.replace('original value', 'modified value');
  route.fulfill({
    response,
    body,
  });
});

This approach is useful for testing how your application handles specific data without changing the backend. 

Simulating Network Errors

To test your application’s resilience to network failures:

await page.route('https://api.example.com/data', route => {
  route.abort('failed');
});

This simulates a network failure for the specified request. 

Best Practices

  • Use Glob Patterns: Utilize glob patterns to match multiple URLs efficiently.
  • Scope Interceptions Appropriately: Apply interceptions at the page or context level as needed to avoid unintended side effects.
  • Clean Up After Tests: Ensure that any routes set up during tests are removed or reset to prevent interference with other tests.

By leveraging Playwright’s request interception capabilities, you can create robust, reliable, and efficient tests that cover a wide range of scenarios, ensuring your application behaves as expected under various conditions.

Leave a Comment

Your email address will not be published. Required fields are marked *