← Volver al listado de tecnologías
Capítulo 9: API Testing
API Testing
Playwright incluye un cliente HTTP para testing de APIs sin necesidad de navegador.
APIRequestContext
import { test, expect } from '@playwright/test';
test('GET request', async ({ request }) => {
const response = await request.get('https://api.example.com/users');
expect(response.ok()).toBeTruthy();
expect(response.status()).toBe(200);
const data = await response.json();
expect(data.length).toBeGreaterThan(0);
});
Métodos HTTP
// GET
const get = await request.get('/api/users');
// POST
const post = await request.post('/api/users', {
data: { name: 'Juan', email: '[email protected]' }
});
// PUT
const put = await request.put('/api/users/1', {
data: { name: 'Juan Actualizado' }
});
// PATCH
const patch = await request.patch('/api/users/1', {
data: { email: '[email protected]' }
});
// DELETE
const del = await request.delete('/api/users/1');
Headers y Autenticación
const response = await request.get('/api/protected', {
headers: {
'Authorization': 'Bearer token123',
'Content-Type': 'application/json'
}
});
Configuración Global
// playwright.config.ts
export default defineConfig({
use: {
baseURL: 'https://api.example.com',
extraHTTPHeaders: {
'Accept': 'application/json',
},
},
});
Combinar UI + API
test('crear usuario via API y verificar en UI', async ({ page, request }) => {
// Crear via API
const response = await request.post('/api/users', {
data: { name: 'Nuevo Usuario' }
});
const user = await response.json();
// Verificar en UI
await page.goto(`/users/${user.id}`);
await expect(page.locator('h1')).toContainText('Nuevo Usuario');
});
Ejercicio Práctico
Objetivo
Testear una API pública (JSONPlaceholder).
Pasos
- Haz GET a
https://jsonplaceholder.typicode.com/posts/1 - Verifica status 200
- Verifica que tiene
titleybody - Haz POST a
/postscon datos nuevos - Verifica que retorna id
Ver solución
import { test, expect } from '@playwright/test';
const BASE_URL = 'https://jsonplaceholder.typicode.com';
test('GET post', async ({ request }) => {
const response = await request.get(`${BASE_URL}/posts/1`);
expect(response.status()).toBe(200);
const post = await response.json();
expect(post).toHaveProperty('title');
expect(post).toHaveProperty('body');
});
test('POST crear post', async ({ request }) => {
const response = await request.post(`${BASE_URL}/posts`, {
data: {
title: 'Mi Post',
body: 'Contenido',
userId: 1
}
});
expect(response.status()).toBe(201);
const post = await response.json();
expect(post).toHaveProperty('id');
});
Criterios de Éxito
- GET funciona correctamente
- POST crea recurso
- Validaciones correctas