I test automatizzati delle applicazioni web richiedono spesso l’interazione con API esterne. Tuttavia, affidarsi alle risposte effettive delle API può introdurre variabili al di fuori del proprio controllo, come problemi di rete o tempi di inattività del server. È qui che entra in gioco il mocking delle API. Il mocking consente di simulare le risposte delle API, rendendo i test più affidabili e veloci. In questo articolo esploreremo come simulare le API usando Playwright con TypeScript.
Mocking API in Playwright
Playwright fornisce un modo per intercettare le richieste di rete e simulare le risposte usando il metodo route
. Vediamo un esempio in cui prendiamo in giro la risposta di un’API.
Guida passo per passo
1. Importare i moduli necessari + creare un test di base
import { test, expect, chromium } from '@playwright/test';
test('Mock User Profile API', async ({ page }) => {
await page.goto('https://example.com/profile');
// Il mock sarà fatto qui
});
2. Impostare l’intercettazione della richiesta e il mock
test('Mock User Profile API', async ({ page }) => {
// Scenario 1: recupero dei dati con successo
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. Aggiungere altri scenari3. Aggiungere altri scenari
test('Mock User Profile API - Empty Profile', async ({ page }) => {
// Scenario 2: Profilo utente vuoto
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: Errore del server
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');
});
Eseguire i test
npx playwright test
Tecniche di mocking avanzate
Playwright consente tecniche di mocking più avanzate, come risposte condizionali o ritardi. Ecco un esempio di mock condizionale:
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');
// Logica di test aggiuntiva qui
});
Si possono anche introdurre ritardi per simulare la latenza della rete:
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');
// Logica di test aggiuntiva qui
});
Conclusione
Il blocco delle API in Playwright con TypeScript è una tecnica potente che migliora l’affidabilità e la velocità dei test. Intercettando le richieste di rete e fornendo risposte personalizzate, è possibile simulare vari scenari e assicurarsi che l’applicazione si comporti come previsto in diverse condizioni.
Spero che questa guida vi aiuti a iniziare a utilizzare il mocking delle API nei test di Playwright. Buon test!
Source:
https://dzone.com/articles/effortless-api-mocking-with-playwright