|

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

beforeEachFixtures
All tests get same setupEach test declares what it needs
No type safetyFull TypeScript types
No auto-cleanupCleanup runs after use()
Shared state risksIsolated 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.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.