In this section, we will explore how to intercept network requests and responses using Playwright. This powerful feature allows you to mock network responses, simulate different network conditions, and test how your application behaves under various scenarios.

Key Concepts

  1. Network Interception: The ability to capture and modify network requests and responses.
  2. Mocking: Simulating network responses to test how your application handles different data.
  3. Route Handling: Using Playwright's routing capabilities to intercept and modify requests.

Why Use Network Interception?

  • Testing Edge Cases: Simulate server errors or slow network conditions.
  • Isolated Testing: Test components without relying on external services.
  • Data Consistency: Ensure consistent test data by mocking responses.

Setting Up Network Interception

To intercept network requests in Playwright, you need to set up routing for the page. Here's a step-by-step guide:

Step 1: Install Playwright

Ensure you have Playwright installed. If not, you can install it using npm:

npm install playwright

Step 2: Basic Script Setup

Create a basic Playwright script to launch a browser and navigate to a page:

import { chromium } from 'playwright';

(async () => {
  const browser = await chromium.launch();
  const context = await browser.newContext();
  const page = await context.newPage();
  await page.goto('https://example.com');
  // More code will be added here
  await browser.close();
})();

Step 3: Intercepting Requests

Use the page.route method to intercept network requests:

await page.route('**/*', (route) => {
  const request = route.request();
  console.log(`Intercepted request to: ${request.url()}`);
  route.continue(); // Continue with the original request
});

Step 4: Mocking Responses

To mock a response, use the route.fulfill method:

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

Practical Example

Let's create a complete example where we intercept and mock a network request:

import { chromium } from 'playwright';

(async () => {
  const browser = await chromium.launch();
  const context = await browser.newContext();
  const page = await context.newPage();

  // Intercept and mock a specific API request
  await page.route('**/api/data', (route) => {
    const mockData = { message: 'Hello, Playwright!' };
    route.fulfill({
      status: 200,
      contentType: 'application/json',
      body: JSON.stringify(mockData),
    });
  });

  await page.goto('https://example.com');
  // Assume there's a script on the page that fetches data from /api/data
  const response = await page.evaluate(async () => {
    const res = await fetch('/api/data');
    return res.json();
  });

  console.log(response); // Output: { message: 'Hello, Playwright!' }

  await browser.close();
})();

Exercise

Task: Write a Playwright script that intercepts requests to an image URL and replaces the image with a placeholder.

Solution:

import { chromium } from 'playwright';

(async () => {
  const browser = await chromium.launch();
  const context = await browser.newContext();
  const page = await context.newPage();

  // Intercept and replace image requests
  await page.route('**/*.png', (route) => {
    route.fulfill({
      status: 200,
      contentType: 'image/png',
      body: Buffer.from('...'), // Placeholder image data
    });
  });

  await page.goto('https://example.com');
  // Check the page to see the placeholder image

  await browser.close();
})();

Common Mistakes:

  • Forgetting to call route.continue() or route.fulfill(), which can cause the request to hang.
  • Not specifying the correct content type in route.fulfill(), leading to incorrect rendering.

Conclusion

Network interception and mocking in Playwright provide a robust way to test your application's behavior under various conditions. By mastering these techniques, you can create more reliable and comprehensive test suites. In the next section, we will explore how to emulate devices and geolocation, further enhancing your testing capabilities.

© Copyright 2024. All rights reserved