DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Resilient API Consumption in Unreliable Enterprise Networks (TypeScript/React)
  • A Beginner’s Guide to Playwright: End-to-End Testing Made Easy
  • Transitioning From Async Storage to Context API in React Native With TypeScript
  • Migrate to VueJS 3, Composition API, and TypeScript?

Trending

  • Building Enterprise-Grade Real-Time IoT Dashboards with Vue 3, MQTT, and Kafka
  • The Agentic Agile Office: Streamlining Enterprise Agile With Autonomous AI Agents
  • Solving the Mystery: Why Java RSS Grows in Docker on M1 Macs
  • Ujorm3: A New Lightweight ORM for JavaBeans and Records
  1. DZone
  2. Data Engineering
  3. Databases
  4. Effortless API Mocking With Playwright

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.

By 
Shivam Bharadwaj user avatar
Shivam Bharadwaj
·
Jul. 24, 24 · Tutorial
Likes (2)
Comment
Save
Tweet
Share
5.9K Views

Join the DZone community and get the full member experience.

Join For Free

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!

API TypeScript

Published at DZone with permission of Shivam Bharadwaj. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Resilient API Consumption in Unreliable Enterprise Networks (TypeScript/React)
  • A Beginner’s Guide to Playwright: End-to-End Testing Made Easy
  • Transitioning From Async Storage to Context API in React Native With TypeScript
  • Migrate to VueJS 3, Composition API, and TypeScript?

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook