使用Playwright进行API模拟的便捷方法

自动化测试网页应用程序通常需要与外部API进行交互。然而,依赖实际API响应可能会引入您无法控制的因素,例如网络问题或服务器宕机。这时API模拟就派上用场了。模拟允许您模拟API响应,使您的测试更加可靠和快速。在本文中,我们将探索如何使用TypeScript使用Playwright来模拟API。

使用Playwright模拟API

Playwright提供了一种通过route方法拦截网络请求并模拟响应的方式。让我们通过一个示例来了解如何模拟API响应。

分步指南

1. 导入所需模块 + 创建基本测试

TypeScript

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

test('Mock User Profile API', async ({ page }) => {
    await page.goto('https://example.com/profile');
    // 模拟将在这里进行
});

2. 设置请求拦截和模拟

TypeScript

test('Mock User Profile API', async ({ page }) => {
    // 场景1:成功数据检索
    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. 添加更多场景

TypeScript

test('Mock User Profile API - Empty Profile', async ({ page }) => {
    // 场景2:空用户资料
    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 }) => {
    // 场景3:服务器错误
    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');
});

运行您的测试

npx playwright test

高级模拟技术

Playwright允许更高级的模拟技术,例如条件响应或延迟。以下是条件模拟的一个例子:

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');
    
    // 额外的测试逻辑在这里
});

您还可以引入延迟来模拟网络延迟:

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');
    
    // 额外的测试逻辑在这里
});

结论

使用TypeScript在Playwright中模拟API是一个增强测试可靠性和速度的强大技术。通过拦截网络请求并提供自定义响应,您可以模拟各种场景并确保您的应用程序在不同的条件下按预期行为运行。

我希望本指南能帮助您开始进行Playwright测试中的API模拟。祝您测试愉快!

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