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
Newsletter
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

  • Why AI Agents Need a Shared Enterprise Ontology
  • Designing Memory Architecture for Stateful AI Agents: Short-Term Context and Long-Term Persistence
  • Multi-Agent Orchestration on AWS With AgentCore Runtime and A2A
  • How to Build Your Own AI SRE From Scratch

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  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
·
Jul. 24, 24 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
6.2K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

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

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • 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