What is a fixture in Playwright?
Written by Jatin Thacker, Automation Architect · Updated
This answer is one piece of Chapter 19: Fixtures.
- Custom Fixtures In-Depth
- Advanced Fixtures
- Building the Fixture Layer
Fixtures are the core dependency injection mechanism in Playwright Test. Instead of relying on mutable global variables or complex before/after hooks across files, tests request the exact resources they need in the test function signature: test('example', async ({ page, context }) => { ... }).
Playwright includes built-in fixtures for common browser primitives: test-scoped fixtures like page (an isolated tab) and context (an isolated browser profile) are isolated between tests, while browser is worker-scoped and reused across tests in the same worker process.
Teams can also define custom fixtures by calling test.extend(), creating reusable dependencies like authenticated user sessions, database clients, or Page Object models. Playwright automatically handles setup order and teardown based on fixture dependencies.
import { test, expect } from '@playwright/test';
test('first test: adds product to cart', async ({ page }) => {
await page.goto('/catalog.html?mock=static&seed=42&autologin=1');
const grinder = page.locator('article[data-sku="MRD-1003"]');
await grinder.getByRole('button', { name: 'Add to cart' }).click();
await expect(page.getByTestId('cart-total')).toHaveText('₹11,900');
});
test('second test: receives fresh context with empty cart', async ({ page }) => {
await page.goto('/catalog.html?mock=static&seed=42&autologin=1');
await expect(page.getByTestId('cart-empty')).toBeVisible();
await expect(page.getByTestId('cart-total')).toHaveText('₹0');
});Running 2 tests using 1 worker ok 1 fixture-isolation.spec.js:3:1 › first test: adds product to cart (1.4s) ok 2 fixture-isolation.spec.js:10:1 › second test: receives fresh context with empty cart (338ms) 2 passed (3.6s)
{ page }. What is the state of the cart in Test B?Related questions
AI can write the test now. The job is knowing whether it checks anything. That's what the course teaches, one chapter at a time.
163 lessons · 226 drills · start free