93 / 139 · 13 Browser Automation with Playwright · Fixtures and Test Data← prev⊞ allnext →☰ Read as one page
10.3Custom Fixtures
Custom fixtures let you extend the test function with your own dependencies:
// fixtures/auth.ts
import { test as base, expect } from '@playwright/test';
import { LoginPage } from '../pages/login.page';
import { DashboardPage } from '../pages/dashboard.page';
type MyFixtures = {
loginPage: LoginPage;
dashboardPage: DashboardPage;
authenticatedPage: DashboardPage;
};
export const test = base.extend<MyFixtures>({
loginPage: async ({ page }, use) => {
const loginPage = new LoginPage(page);
await loginPage.goto();
await use(loginPage);
},
dashboardPage: async ({ page }, use) => {
await use(new DashboardPage(page));
},
authenticatedPage: async ({ page }, use) => {
const loginPage = new LoginPage(page);
await loginPage.goto();
await loginPage.login('test@example.com', 'password');
await use(new DashboardPage(page));
},
});
export { expect };
Using Custom Fixtures
// tests/dashboard.spec.ts
import { test, expect } from '../fixtures/auth';
// Receives an already-authenticated dashboard page
test('dashboard shows user name', async ({ authenticatedPage }) => {
await expect(authenticatedPage.userName).toHaveText('Test User');
});
// Receives just the login page
test('invalid login shows error', async ({ loginPage }) => {
await loginPage.login('bad@test.com', 'wrong');
expect(await loginPage.getErrorMessage()).toContain('Invalid');
});