Day 6: Fixtures — Dependency Injection That Eliminates Boilerplate
This is Day 6 of the 21-Day Playwright with TypeScript Challenge. One lesson per day. Zero to production-ready in 3 weeks.
🎭 Want to master this with real projects? Join the Playwright Automation Mastery course at The Testing Academy.
Fixtures inject dependencies into tests. No more repeated beforeEach setup. No more inheritance chains. Each test declares what it needs, fixtures provide it.
Contents
Built-in Fixtures
test('uses built-in fixtures', async ({ page, context, browser, request }) => {
// page — browser tab (most common)
// context — isolated session (cookies, storage)
// browser — browser instance
// request — API client (no browser needed)
});
Custom Fixtures
// src/fixtures/index.ts
import { test as base } from '@playwright/test';
import { LoginPage } from '../pages/LoginPage';
import { DashboardPage } from '../pages/DashboardPage';
type MyFixtures = {
loginPage: LoginPage;
dashboardPage: DashboardPage;
authenticatedPage: LoginPage;
};
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('admin@test.com', 'password');
await use(loginPage);
// Cleanup runs after test
},
});
export { expect } from '@playwright/test';
🚀 Level Up Your Playwright
From locators to CI pipelines — build a production-grade Playwright + TypeScript framework step by step.
Using Custom Fixtures
// tests/dashboard.spec.ts
import { test, expect } from '../src/fixtures';
test('dashboard shows user name', async ({ authenticatedPage, page }) => {
// authenticatedPage already logged in!
await page.goto('/dashboard');
await expect(page.getByText('Welcome, admin')).toBeVisible();
});
Why Fixtures Beat beforeEach
| beforeEach | Fixtures |
|---|---|
| All tests get same setup | Each test declares what it needs |
| No type safety | Full TypeScript types |
| No auto-cleanup | Cleanup runs after use() |
| Shared state risks | Isolated per test |
Tomorrow (Day 7): API testing — validate backend without a browser.
🎓 Master Playwright End to End
Join hundreds of SDETs building real automation frameworks. Lifetime access, hands-on projects, and a job-ready portfolio.
