הדמיית API ללא מאמץ עם Playwright

בדיוקים במבחן המקרי שלך בעזרת פלייוייסט, אתה יכול להדמיין תגובות ל API שלך. זה מאפשר לך לבדוק את התוצאות שלך מבלי להיות מסוגל לסמוך על תגובות אמיתיות של API. זוהי דרכך להגביר את האמינות והמהירות של הבדיקות שלך. במאמר הזה, אנחנו נלך דרך איך לדמות API בעזרת פלייוייסט עם טייפסקייפ.

דמיית API בפלייוייסט

פלייוייסט מעניק דרך לעריכת דרכים ודמיית תגובות בעזרת השיטה 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

טכניקות דמיון מתקדמות

פלייוייסט מאפשר טכניקות דמיון מתקדמות, כמו תגובות תנאים או האטמציות. פה דוגמה של דמיון תנאים:

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');
    
    // העבודה הנוספת שלך כאן
});

סיקור הסיום

מחיקת אפיינים בפלייוריסט עם טאייפסקייפ היא טכניקה חזקה שמעלה את האמינות והמהירות של הבדיקות שלך. על-ידי הפעלת מבט דרך בבקשות רשת וספקת תגובות מותאמות, אתה יכול לסימולט מצבים שונים ולוודא שהיישומך מתהגה כפי שצפוי תחת תנאים שונים.

אני מקווה שהדרכה הזו תעזור לך להתחיל עם הדמיית אפיינים בבדיקות שלך בפלייוריסט. בדיקות שמח!

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