Lesson 4
Mocking API Requests in Playwright
Introduction to Mocking API Requests

Welcome! As we continue our exploration of automated testing with Playwright, we arrive at a crucial skill — mocking API requests. This lesson will guide you through the process of intercepting and altering network requests to create more controlled testing environments. Mocking API requests is essential for situations where the actual API may not be available, or to test specific response scenarios without altering the backend.

What You'll Learn

In this lesson, you'll learn how to mock API requests using Playwright's robust capabilities. This includes intercepting HTTP requests and providing custom responses. Here’s a glimpse at a practical code example for mocking book data:

TypeScript
1import { test, expect } from '@playwright/test'; 2 3test('mocking API response for book data', async ({ page }) => { 4 await page.route('http://localhost:3000/api/books', route => { 5 route.fulfill({ 6 status: 200, 7 contentType: 'application/json', 8 body: JSON.stringify([ 9 { id: 101, title: 'Mock Book', author: 'Mock Author', price: 99.99, category: 'Mock Category' } 10 ]), 11 }); 12 }); 13 14 await page.goto('http://localhost:3000/books'); 15 16 const bookTitle = await page.textContent('.book-title'); 17 expect(bookTitle).toBe('Mock Book'); 18});

In the above example, you'll see:

  • Route Interception: page.route() is used to intercept requests to the specified API endpoint.
  • Mock Response: route.fulfill() is employed to provide a mock response with customized data.
  • Assertion: The test concludes by verifying that the mocked data is correctly rendered in the UI.

This approach ensures you can test your application under various controlled conditions without depending on the live API.

Why It Matters

Mocking API requests is a powerful technique. It allows developers to:

  • Isolate Tests: Focus solely on the client-side logic without being affected by backend changes or downtimes.
  • Simulate Rare Scenarios: Test edge cases and error responses that may be difficult to reproduce with the actual API.
  • Enhance Test Speed: Reduce the latency and variability inherent in network-bound tests, leading to faster test execution.

Mastering the skill of mocking API requests paves the way toward more reliable and flexible automated tests. By the end of this section, you'll have the skills necessary to create resilient tests that are less reliant on external systems. Now, let’s dive into practice!

Enjoy this lesson? Now it's time to practice with Cosmo!
Practice is how you turn knowledge into actual skills.