Effortless API Mocking With Playwright

Automated testing of web applications often requires interaction with external APIs. However, relying on actual API responses can introduce variables beyond your control, such as network issues or server downtime. This is where API mocking comes in. Mocking allows you to simulate API responses, making your tests more reliable and faster. In this article, we’ll explore how to mock APIs using Playwright with TypeScript.

Mocking APIs in Playwright

Playwright provides a way to intercept network requests and mock responses using the route method. Let’s walk through an example where we mock an API response.

Step-By-Step Guide

1. Import the Necessary Modules + Create a Basic Test

TypeScript

import { test, expect, chromium } from '@playwright/test';

test('Mock User Profile API', async ({ page }) => {
    await page.goto('https://example.com/profile');
    // Mocking will be done here
});

2. Set Up Request Interception and Mocking

TypeScript

test('Mock User Profile API', async ({ page }) => {
    // Scenario 1: Successful data retrieval
    await page.route('https://api.example.com/user/profile', route => {
        const mockResponse = {
            status: 200,
            contentType: 'application/json',
            body: JSON.stringify({
                name: 'John Doe',
                email: '[email protected]',
                age: 30
            })
        };
        route.fulfill(mockResponse);
    });

    await page.goto('https://example.com/profile');
    
    const userName = await page.textContent('#name'); // Assuming the name is rendered in an element with id 'name'
    const userEmail = await page.textContent('#email'); // Assuming the email is rendered in an element with id 'email'
    const userAge = await page.textContent('#age'); // Assuming the age is rendered in an element with id 'age'
    
    expect(userName).toBe('John Doe');
    expect(userEmail).toBe('[email protected]');
    expect(userAge).toBe('30');
});

3. Add More Scenarios

TypeScript

test('Mock User Profile API - Empty Profile', async ({ page }) => {
    // Scenario 2: Empty user profile
    await page.route('https://api.example.com/user/profile', route => {
        const mockResponse = {
            status: 200,
            contentType: 'application/json',
            body: JSON.stringify({})
        };
        route.fulfill(mockResponse);
    });

    await page.goto('https://example.com/profile');
    
    const userName = await page.textContent('#name');
    const userEmail = await page.textContent('#email');
    const userAge = await page.textContent('#age');
    
    expect(userName).toBe('');
    expect(userEmail).toBe('');
    expect(userAge).toBe('');
});

test('Mock User Profile API - Server Error', async ({ page }) => {
    // Scenario 3: Server error
    await page.route('https://api.example.com/user/profile', route => {
        const mockResponse = {
            status: 500,
            contentType: 'application/json',
            body: JSON.stringify({ error: 'Internal Server Error' })
        };
        route.fulfill(mockResponse);
    });

    await page.goto('https://example.com/profile');
    const errorMessage = await page.textContent('#error'); // Assuming the error message is rendered in an element with id 'error'
    expect(errorMessage).toBe('Internal Server Error');
});

Running Your Tests

npx playwright test

Advanced Mocking Techniques

Playwright allows more advanced mocking techniques, such as conditional responses or delays. Here’s an example of a conditional mock:

TypeScript

test('Conditional Mocking', async ({ page }) => {
    await page.route('https://api.example.com/user/profile', route => {
        if (route.request().method() === 'POST') {
            route.fulfill({
                status: 201,
                contentType: 'application/json',
                body: JSON.stringify({ message: 'Profile created' })
            });
        } else {
            route.fulfill({
                status: 200,
                contentType: 'application/json',
                body: JSON.stringify({
                    name: 'John Doe',
                    email: '[email protected]',
                    age: 30
                })
            });
        }
    });

    await page.goto('https://example.com/profile');
    
    // Additional test logic here
});

You can also introduce delays to simulate network latency:

TypeScript

test('Mock with Delay', async ({ page }) => {
    await page.route('https://api.example.com/user/profile', async route => {
        await new Promise(res => setTimeout(res, 2000)); // Delay for 2 seconds
        route.fulfill({
            status: 200,
            contentType: 'application/json',
            body: JSON.stringify({
                name: 'John Doe',
                email: '[email protected]',
                age: 30
            })
        });
    });

    await page.goto('https://example.com/profile');
    
    // Additional test logic here
});

Conclusion

Mocking APIs in Playwright with TypeScript is a powerful technique that enhances the reliability and speed of your tests. By intercepting network requests and providing custom responses, you can simulate various scenarios and ensure your application behaves as expected under different conditions.

I hope this guide helps you get started with API mocking in your Playwright tests. Happy testing!

Source:
https://dzone.com/articles/effortless-api-mocking-with-playwright