Playwright Fixtures Explained With Examples


If you have started writing Playwright tests, you have probably seen code like this:

test('user can login', async ({ page }) => {

  await page.goto('/login');

});


But what exactly is { page }?

It is a Playwright fixture.

Fixtures are one of the most useful features in Playwright Test because they prepare the environment your test needs. Instead of writing the same setup code repeatedly, you can create reusable fixtures and inject them into tests.

In this guide, we will understand Playwright fixtures from the beginning and then create practical custom examples.

What Are Playwright Fixtures?

A Playwright fixture is a reusable setup mechanism that provides a test with everything it needs to run.

For example:

test('homepage test', async ({ page }) => {

  await page.goto('/');

});


Here, page is a built-in fixture.

Playwright creates the page for the test and manages its lifecycle.

Official Playwright documentation explains that fixtures establish the environment for each test and provide only the fixtures required by that test.

In simple words:

A fixture prepares something before a test and manages what happens to it around the test.

Why Are Fixtures Important?

Imagine 50 tests need a logged-in user.

Without fixtures, you might repeat:

await page.goto('/login');

await page.getByLabel('Email').fill('user@example.com');

await page.getByLabel('Password').fill('password');

await page.getByRole('button', { name: 'Login' }).click();


in many tests.

That creates duplication.

With a fixture, you can prepare the login environment once and reuse it.

This gives you:

  • Less duplicate code

  • Cleaner tests

  • Better reuse

  • Easier maintenance

  • Better test isolation

  • Centralized setup

  • Easier scaling

Built-In Playwright Fixtures

Playwright Test provides several built-in fixtures.

Fixture

Purpose

page

Provides a browser page

context

Provides an isolated BrowserContext

browser

Provides a browser instance

request

Provides API request capabilities

browserName

Identifies the browser

page

Commonly used for UI testing

A basic example:

import { test, expect } from '@playwright/test';


test('homepage works', async ({ page }) => {

  await page.goto('https://example.com');


  await expect(page).toHaveTitle(/Example/);

});


The test does not create the browser page manually. Playwright Test supplies it through the fixture system.

How Does Fixture Injection Work?

Look at this:

test('search test', async ({ page }) => {

  // test

});


The { page } parameter tells Playwright:

"This test needs the page fixture."

Playwright then prepares the fixture and passes it into the test.

If the test does not need another fixture, there is no reason to create or request it.

This on-demand behavior is one of the strengths of Playwright fixtures.

Fixture Lifecycle

A simplified lifecycle looks like this:

Create fixture

      ↓

Prepare environment

      ↓

Run test

      ↓

Clean up fixture


For example, the page fixture is created for the test and cleaned up after the test completes.

This isolation helps prevent one test from accidentally affecting another.

What Is a Custom Fixture?

A custom fixture is a fixture created by you for your project.

For example, suppose every test needs a LoginPage object.

Instead of creating it manually:

const loginPage = new LoginPage(page);


in every test, you can create a fixture.

import { test as base } from '@playwright/test';

import { LoginPage } from '../pages/LoginPage';


type Fixtures = {

  loginPage: LoginPage;

};


export const test = base.extend<Fixtures>({

  loginPage: async ({ page }, use) => {

    const loginPage = new LoginPage(page);


    await use(loginPage);

  },

});


Now the test can simply use:

test('login test', async ({ loginPage }) => {

  await loginPage.login(

    'user@example.com',

    'password'

  );

});


This is much cleaner in a larger project.

Fixtures and Page Object Model

Fixtures and Page Object Model work very well together.

A Page Object contains page behavior.

A fixture controls how that Page Object becomes available to tests.

For example:

Test

 ↓

Fixture

 ↓

Page Object

 ↓

Playwright Page

 ↓

Browser


This separation keeps responsibilities clear.

If you are learning POM, connect this topic with the [Page Object Model] guide and then practice it through [Playwright Projects].

A Practical Logged-In Fixture

Suppose your application requires authentication.

You can create a fixture that opens the application and logs in.

import { test as base } from '@playwright/test';


type MyFixtures = {

  authenticatedPage: void;

};


export const test = base.extend<MyFixtures>({

  authenticatedPage: async ({ page }, use) => {


    await page.goto('/login');


    await page.getByLabel('Email')

      .fill('user@example.com');


    await page.getByLabel('Password')

      .fill('password');


    await page.getByRole('button', {

      name: 'Login'

    }).click();


    await page.waitForURL('**/dashboard');


    await use();

  }

});


A test can now use:

test('dashboard is visible', async ({

  page,

  authenticatedPage

}) => {

  await expect(

    page.getByRole('heading', {

      name: 'Dashboard'

    })

  ).toBeVisible();

});


The test does not need to know how authentication was performed.

The use() Function

One important concept in custom fixtures is use().

Consider:

loginPage: async ({ page }, use) => {

  const loginPage = new LoginPage(page);


  await use(loginPage);

}


Think of use() as the point where the prepared fixture is handed to the test.

Code before use() is setup.

Code after use() can be used for teardown.

For example:

myFixture: async ({ page }, use) => {


  console.log('Setup');


  await use(page);


  console.log('Cleanup');

}


The basic flow is:

Setup

  ↓

use()

  ↓

Test uses fixture

  ↓

Teardown


Test-Scoped Fixtures

A test-scoped fixture is created for a test and cleaned up after that test.

This is useful for things that should remain isolated.

Examples include:

  • Pages

  • Test users

  • Temporary files

  • Test data

  • Page Objects

Test isolation is important because one test should not depend on another test's state.

Worker-Scoped Fixtures

Playwright also supports worker-scoped fixtures.

A worker fixture is shared by tests running inside the same worker process.

This can be useful for expensive setup operations.

For example:

workerResource: [

  async ({}, use) => {


    console.log('Create worker resource');


    await use();


    console.log('Destroy worker resource');


  },

  { scope: 'worker' }

]


Worker-scoped fixtures are useful when something should be prepared once for a worker instead of once per test.

Playwright's documentation notes that worker-scoped fixtures are set up once for a worker process and reused by compatible tests in that worker.

Automatic Fixtures

Normally, a fixture runs when a test asks for it.

An automatic fixture can run automatically.

For example:

export const test = base.extend({

  logging: [

    async ({}, use) => {


      console.log('Test started');


      await use();


      console.log('Test finished');


    },

    { auto: true }

  ]

});


The test does not need to include logging in its parameters.

This can be useful for cross-cutting functionality such as:

  • Logging

  • Diagnostics

  • Environment preparation

  • Common cleanup

However, automatic fixtures should be used carefully. If too many run automatically, the test framework can become difficult to understand.

Fixtures vs Hooks

Fixtures and hooks are related but different.

Fixtures

Hooks

Provide reusable resources

Run setup/cleanup code

Can be composed

Usually tied to test lifecycle

Can be test or worker scoped

Can be before/after test or suite

Can inject objects into tests

Commonly perform actions

Good for reusable environments

Good for simple lifecycle actions

For example, a beforeEach hook could navigate to a page.

A custom fixture could provide an authenticated page object.

Fixtures and Hooks Can Work Together

Fixtures can also be used inside hooks.

For example:

test.beforeEach(async ({ page }) => {

  await page.goto('/');

});


The page fixture is supplied to the hook.

Playwright documents that fixtures can be used by tests, hooks, annotations, and other fixtures.

Fixture Dependencies

Fixtures can depend on other fixtures.

For example:

type Fixtures = {

  user: {

    email: string;

    password: string;

  };

  loggedInPage: void;

};


Then:

loggedInPage: async ({ page, user }, use) => {


  await page.goto('/login');


  await page.getByLabel('Email')

    .fill(user.email);


  await page.getByLabel('Password')

    .fill(user.password);


  await page.getByRole('button', {

    name: 'Login'

  }).click();


  await use();

}


Here, loggedInPage depends on both page and user.

This makes fixtures composable.

Fixtures for API Testing

The request fixture can be used for API testing.

For example:

test('API returns user', async ({ request }) => {


  const response = await request.get('/api/users/1');


  expect(response.ok()).toBeTruthy();


  const data = await response.json();


  expect(data.id).toBe(1);

});


Playwright's API testing functionality can also be used to prepare backend state before a browser test.

This is useful when UI setup would take too long.

Fixtures for Page Objects

A larger framework can provide Page Objects through fixtures.

For example:

export const test = base.extend<{

  dashboardPage: DashboardPage;

}>({

  dashboardPage: async ({ page }, use) => {


    const dashboard =

      new DashboardPage(page);


    await use(dashboard);

  }

});


Then:

test('dashboard test', async ({

  dashboardPage

}) => {


  await dashboardPage.open();


  await dashboardPage.verifyDashboard();

});


The test now describes behavior instead of construction details.

Common Fixture Mistakes

1. Creating fixtures for everything

Not every helper function needs to become a fixture.

Use fixtures when the reusable lifecycle or dependency adds real value.

2. Creating huge fixtures

A fixture should have one clear responsibility.

3. Hiding important test behavior

If a fixture performs ten major business actions, the actual test may become difficult to understand.

4. Sharing mutable data

Be careful when multiple tests modify the same server-side data.

5. Using worker scope incorrectly

Worker-scoped resources are shared across tests in a worker, so they need careful isolation.

6. Forgetting cleanup

Resources created by a fixture should be cleaned up when appropriate.

Best Practices for Playwright Fixtures

Use these guidelines:

  • Give fixtures clear names.

  • Keep each fixture focused.

  • Use TypeScript types for custom fixtures.

  • Prefer test scope for isolated test resources.

  • Use worker scope for genuinely shared worker-level setup.

  • Use fixtures with Page Objects when appropriate.

  • Avoid unnecessary automatic fixtures.

  • Keep secrets out of fixture source code.

  • Keep business logic understandable.

  • Document complicated fixtures.

  • Use fixtures to reduce duplication, not to hide test behavior.

Frequently Asked Questions

What are Playwright fixtures?

Playwright fixtures are reusable setup and teardown mechanisms that provide tests with the resources and environment they need.

Is page a Playwright fixture?

Yes. page is one of the built-in Playwright Test fixtures.

Can I create my own fixture?

Yes. Playwright Test allows you to extend the base test object and create custom fixtures.

What is the difference between test and worker fixtures?

Test-scoped fixtures are associated with individual tests. Worker-scoped fixtures are associated with a worker process and can be reused by tests in that worker.

Can fixtures be used with Page Object Model?

Yes. Fixtures can create and provide Page Object instances to tests.

Can fixtures perform login?

Yes. Authentication is a common use case, although Playwright also provides dedicated authentication-state patterns for larger suites.

Should I use fixtures instead of beforeEach?

Not always. Use hooks when a simple lifecycle action is appropriate. Use fixtures when you need a reusable, composable resource or environment.

Conclusion

Playwright fixtures are more than a convenient way to shorten test code.

They provide a structured way to prepare test environments, share reusable resources, isolate tests, and build scalable automation architecture.

Start with built-in fixtures such as:

page

context

browser

request


Then introduce custom fixtures when your project starts repeating setup logic.

A good fixture should make a test easier to understand—not make the test's behavior mysterious.

Once you understand fixtures, the next useful topics are [Playwright Assertions], [Playwright Locators], and real-world [Playwright Projects]. Together, these concepts form an important foundation for maintainable Playwright automation.


 

Comments

Popular posts from this blog

How to Run Only Smoke Tests in Playwright: Step-by-Step Guide

How to Test REST APIs Using Playwright

Playwright Multiple Tabs and Windows Explained: A Practical Guide