← Volver al listado de tecnologías
Capítulo 8: Fixtures y Hooks
Fixtures y Hooks
Los fixtures y hooks permiten compartir configuración y estado entre tests.
Hooks Básicos
import { test } from '@playwright/test';
test.beforeAll(async () => {
// Ejecuta una vez antes de todos los tests
console.log('Setup global');
});
test.beforeEach(async ({ page }) => {
// Ejecuta antes de cada test
await page.goto('/');
});
test.afterEach(async ({ page }) => {
// Ejecuta después de cada test
await page.screenshot({ path: 'screenshot.png' });
});
test.afterAll(async () => {
// Ejecuta una vez después de todos los tests
console.log('Cleanup global');
});
Fixtures Personalizados
// fixtures.ts
import { test as base } from '@playwright/test';
import { TodoPage } from './pages/todo.page';
type MyFixtures = {
todoPage: TodoPage;
};
export const test = base.extend<MyFixtures>({
todoPage: async ({ page }, use) => {
const todoPage = new TodoPage(page);
await todoPage.goto();
await use(todoPage);
},
});
export { expect } from '@playwright/test';
Uso de Fixtures
// tests/todo.spec.ts
import { test, expect } from '../fixtures';
test('agregar tarea', async ({ todoPage }) => {
// todoPage ya está inicializado y navegado
await todoPage.addTodo('Mi tarea');
expect(await todoPage.getTodoCount()).toBe(1);
});
Fixture de Usuario Autenticado
// fixtures.ts
export const test = base.extend({
authenticatedPage: async ({ browser }, use) => {
const context = await browser.newContext({
storageState: 'auth.json'
});
const page = await context.newPage();
await use(page);
await context.close();
},
});
Guardar Estado de Autenticación
// global-setup.ts
import { chromium } from '@playwright/test';
async function globalSetup() {
const browser = await chromium.launch();
const page = await browser.newPage();
await page.goto('/login');
await page.fill('#email', '[email protected]');
await page.fill('#password', 'password');
await page.click('button[type="submit"]');
await page.context().storageState({ path: 'auth.json' });
await browser.close();
}
export default globalSetup;
Ejercicio Práctico
Objetivo
Crear un fixture que inicialice TodoMVC con 3 tareas predefinidas.
Pasos
- Crea archivo
fixtures.ts - Define fixture
todoPageWithTasks - El fixture debe crear 3 tareas automáticamente
- Usa el fixture en un test
Ver solución
// fixtures.ts
import { test as base } from '@playwright/test';
import { TodoPage } from './pages/todo.page';
export const test = base.extend({
todoPageWithTasks: async ({ page }, use) => {
const todoPage = new TodoPage(page);
await todoPage.goto();
await todoPage.addTodo('Tarea 1');
await todoPage.addTodo('Tarea 2');
await todoPage.addTodo('Tarea 3');
await use(todoPage);
},
});
// tests/todo.spec.ts
test('ya tiene 3 tareas', async ({ todoPageWithTasks }) => {
expect(await todoPageWithTasks.getTodoCount()).toBe(3);
});
Criterios de Éxito
- Fixture creado
- 3 tareas agregadas automáticamente
- Test usa el fixture correctamente