Back to All Questions
Question 5 of 100
Framework
Advanced
Explain Fixtures in Playwright.
The Answer
Fixtures are Playwright's dependency injection system for tests. They provide isolated, reusable setup/teardown logic. Unlike `beforeEach`, fixtures are composable, type-safe, lazy (only created when requested), and can be shared across test files.
Deep Dive Explanation
The `use()` callback is the dividing line between setup (before `use()`) and teardown (after `use()`). Teardown always runs, even if the test throws an exception β guaranteed cleanup. This is superior to `afterEach` hooks which can be skipped if `beforeEach` throws.
example.spec.ts
import { test as base, expect } from '@playwright/test';
// Define a custom 'loggedInPage' fixture
const test = base.extend<{ loggedInPage: Page }>({
loggedInPage: async ({ page }, use) => {
// SETUP: runs before test
await page.goto('/login');
await page.getByLabel('Email').fill('admin@example.com');
await page.getByLabel('Password').fill('secret');
await page.getByRole('button', { name: 'Sign In' }).click();
await page.waitForURL('/dashboard');
await use(page); // β TEST RUNS HERE
// TEARDOWN: runs after test (even if test fails)
await page.goto('/logout');
}
});
test('uses logged in page', async ({ loggedInPage }) => {
await expect(loggedInPage.getByText('Welcome, Admin')).toBeVisible();
});