← Volver al listado de tecnologías
Capítulo 6: Assertions
Assertions
Las assertions en Playwright son “web-first”: reintentan automáticamente hasta que pasan o expira el timeout.
Assertions de Página
// Título
await expect(page).toHaveTitle('Mi Página');
await expect(page).toHaveTitle(/Página/);
// URL
await expect(page).toHaveURL('https://ejemplo.com/dashboard');
await expect(page).toHaveURL(/dashboard/);
Assertions de Elementos
const elemento = page.locator('.mi-elemento');
// Visibilidad
await expect(elemento).toBeVisible();
await expect(elemento).toBeHidden();
// Habilitado/Deshabilitado
await expect(elemento).toBeEnabled();
await expect(elemento).toBeDisabled();
// Texto
await expect(elemento).toHaveText('Texto exacto');
await expect(elemento).toContainText('parcial');
// Atributos
await expect(elemento).toHaveAttribute('href', '/link');
await expect(elemento).toHaveClass(/activo/);
// Valor de input
await expect(elemento).toHaveValue('valor');
// Checkbox/Radio
await expect(elemento).toBeChecked();
// Cantidad
await expect(page.locator('li')).toHaveCount(5);
Assertions Negativas
await expect(elemento).not.toBeVisible();
await expect(elemento).not.toHaveText('No este texto');
Soft Assertions
No detienen el test al fallar:
await expect.soft(elemento).toHaveText('Texto');
await expect.soft(otro).toBeVisible();
// El test continúa aunque falle
Timeouts Personalizados
await expect(elemento).toBeVisible({ timeout: 10000 });
Ejercicio Práctico
Objetivo
Practicar diferentes tipos de assertions.
Pasos
- Navega a
https://demo.playwright.dev/todomvc - Verifica que el título contiene “TodoMVC”
- Agrega una tarea y verifica que aparece
- Verifica que el contador muestra “1 item left”
- Marca la tarea y verifica el checkbox
Ver solución
import { test, expect } from '@playwright/test';
test('assertions en TodoMVC', async ({ page }) => {
await page.goto('https://demo.playwright.dev/todomvc');
await expect(page).toHaveTitle(/TodoMVC/);
const input = page.getByPlaceholder('What needs to be done?');
await input.fill('Mi tarea');
await input.press('Enter');
await expect(page.getByText('Mi tarea')).toBeVisible();
await expect(page.locator('.todo-count')).toContainText('1 item');
const checkbox = page.getByRole('checkbox');
await checkbox.check();
await expect(checkbox).toBeChecked();
});
Criterios de Éxito
- Usaste al menos 4 tipos de assertions
- Todas las validaciones pasan
- Entiendes el auto-retry