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
- Network Interception: The ability to capture and modify network requests and responses.
- Mocking: Simulating network responses to test how your application handles different data.
- 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:
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()
orroute.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.
Playwright with TypeScript: From Beginner to Advanced
Module 1: Introduction to Playwright and TypeScript
- What is Playwright?
- Setting Up Your Development Environment
- Introduction to TypeScript
- Basic TypeScript Syntax
Module 2: Getting Started with Playwright
- Installing Playwright
- Creating Your First Playwright Script
- Understanding Playwright's Core Concepts
- Running Playwright Tests
Module 3: Playwright and TypeScript Basics
- Writing Tests in TypeScript
- Using TypeScript Interfaces and Types
- Debugging Playwright Tests
- Handling Asynchronous Code
Module 4: Advanced Playwright Features
- Working with Selectors
- Handling Multiple Pages and Frames
- Network Interception and Mocking
- Emulating Devices and Geolocation
Module 5: Test Automation Strategies
- Organizing Tests and Test Suites
- Using Fixtures and Hooks
- Parallel Test Execution
- Continuous Integration with Playwright
Module 6: Advanced TypeScript Techniques
- Generics in TypeScript
- Advanced TypeScript Types
- TypeScript Decorators
- TypeScript and Playwright Best Practices
Module 7: Real-World Playwright Applications
- End-to-End Testing with Playwright
- Visual Testing with Playwright
- Performance Testing with Playwright
- Case Study: Implementing Playwright in a Project