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
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Transitioning From Async Storage to Context API in React Native With TypeScript
  • Migrate to VueJS 3, Composition API, and TypeScript?
  • TDD Typescript NestJS API Layers with Jest Part 3: Repository Unit Test
  • TDD Typescript NestJS API Layers with Jest Part 1: Controller Unit Test

Trending

  • Integrating Security as Code: A Necessity for DevSecOps
  • Unlocking the Potential of Apache Iceberg: A Comprehensive Analysis
  • Beyond ChatGPT, AI Reasoning 2.0: Engineering AI Models With Human-Like Reasoning
  • Measuring the Impact of AI on Software Engineering Productivity
  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.2K 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: 'john.doe@example.com',
                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('john.doe@example.com');
    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: 'john.doe@example.com',
                    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: 'john.doe@example.com',
                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

  • Transitioning From Async Storage to Context API in React Native With TypeScript
  • Migrate to VueJS 3, Composition API, and TypeScript?
  • TDD Typescript NestJS API Layers with Jest Part 3: Repository Unit Test
  • TDD Typescript NestJS API Layers with Jest Part 1: Controller Unit Test

Partner Resources

×

Comments
Oops! Something Went Wrong

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

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

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 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!