Menu
×
   ❮   
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP C C++ C# AWS W3.CSS HOW TO BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS DSA TYPESCRIPT ANGULAR ANGULARJS GIT POSTGRESQL MONGODB ASP AI R GO KOTLIN SWIFT SASS VUE GEN AI SCIPY CYBERSECURITY DATA SCIENCE INTRO TO PROGRAMMING HTML & CSS BASH RUST TOOLS MATH

Playwright Fixtures


Share

Playwright Fixtures

A fixture is something Playwright prepares for a test before it runs, and cleans up after.

You have used one in every test so far: page.

You ask for a fixture by writing its name in the first argument of the test function:

Example

test('my test', async ({ page }) => {
  // page is ready to use here
});

Playwright only sets up the fixtures a test asks for.


Built-in Fixtures

Playwright Test comes with these fixtures:

FixtureWhat it is
pageA new browser tab, made for this test only
contextThe browser context of the page. A browser context is like a new, empty browser profile, with its own cookies and storage
browserThe browser, shared by the tests in the same worker
browserNameThe name of the browser: chromium, firefox or webkit
requestAn API client for HTTP requests, without a browser (see API Testing)

The test function also gets a second argument, testInfo, with information about the running test:

Example

tests/builtin.spec.js

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

test('uses built-in fixtures', async ({ page, context, browserName }, testInfo) => {
  console.log('Browser:', browserName);
  console.log('Test:', testInfo.title);
  console.log('Pages in context:', context.pages().length);
  await page.goto('todo.html');
  await expect(page).toHaveTitle(/Todo List/);
});

test('request fixture calls the API', async ({ request }) => {
  const response = await request.get('api/products.php');
  expect(response.status()).toBe(200);
});

Run it with the list reporter to see the logs:

Example

npx playwright test --reporter=list

Output:

Running 2 tests using 2 workers

  ok 1 [chromium] › tests/builtin.spec.js:12:1 › request fixture calls the API (56ms)
Browser: chromium
Test: uses built-in fixtures
Pages in context: 1
  ok 2 [chromium] › tests/builtin.spec.js:4:1 › uses built-in fixtures (195ms)

  2 passed (1.8s)

The second test never opened a browser page, because it only asked for request.



Create Your Own Fixtures

Use test.extend() to make a new test function with extra fixtures.

This file adds two fixtures, using the page objects from the Page Object Model chapter:

Example

fixtures.js

// @ts-check
import { test as base, expect } from '@playwright/test';
import { TodoPage } from './pages/todo-page';
import { LoginPage } from './pages/login-page';

export const test = base.extend({
  todoPage: async ({ page }, use) => {
    const todoPage = new TodoPage(page);
    await todoPage.goto();
    await use(todoPage);
  },

  loggedInPage: async ({ page }, use) => {
    const loginPage = new LoginPage(page);
    await loginPage.goto();
    await loginPage.login('student', 'w3schools');
    await expect(loginPage.welcome).toBeVisible();
    await use(page);
  },
});

export { expect };

Example Explained

  • base.extend({ ... }) returns a new test that has all the built-in fixtures plus yours
  • A fixture is an async function. Its first argument gives it other fixtures, here page
  • The code before use() is the setup
  • await use(value) gives the value to the test, and waits until the test is done
  • Code after use() would be the cleanup (these two fixtures need none)
  • todoPage gives the test a Todo List page object that is already open
  • loggedInPage gives the test a page where the user is already logged in

Use Custom Fixtures

Import test and expect from your fixtures file instead of from @playwright/test.

Then ask for your fixtures by name:

Example

tests/todo.spec.js

// @ts-check
import { test, expect } from '../fixtures';

test('can add a todo', async ({ todoPage }) => {
  await todoPage.addTodo('Learn Playwright');
  await todoPage.expectCount('1 item left');
});

test('can complete a todo', async ({ todoPage }) => {
  await todoPage.addTodo('Learn Playwright');
  await todoPage.completeTodo('Learn Playwright');
  await todoPage.expectCount('0 items left');
});

test('logged in user can open the shop', async ({ loggedInPage }) => {
  await loggedInPage.getByRole('link', { name: 'Go to the shop' }).click();
  await expect(loggedInPage).toHaveTitle(/Shop/);
});

Output:

Running 3 tests using 3 workers

[1/3] [chromium] › tests/todo.spec.js:15:1 › logged in user can open the shop
[2/3] [chromium] › tests/todo.spec.js:9:1 › can complete a todo
[3/3] [chromium] › tests/todo.spec.js:4:1 › can add a todo
  3 passed (3.5s)

Each test starts with the part it really tests.

No new TodoPage(page), no goto(), no login steps.

Note: Fixtures are often a better choice than beforeEach hooks.

A hook runs for every test in the file, but a fixture only runs for the tests that ask for it.


Test Scope and Worker Scope

By default a fixture has test scope: it is set up again for every test.

A fixture with worker scope is set up once per worker process, and shared by all tests in that worker.

Use it for slow setup that tests can safely share, like data from an API.

This fixture goes inside base.extend({ ... }), like the fixtures above:

Example

productCount: [async ({ playwright }, use) => {
  const api = await playwright.request.newContext({ baseURL: 'https://www.w3schools.com/playwright/practice/' });
  const data = await (await api.get('api/products.php')).json();
  await use(data.products.length);
  await api.dispose();
}, { scope: 'worker' }],

The fixture is written as an array: the function, then an options object.

The playwright fixture gives access to the Playwright library.

playwright.request.newContext() creates an API client, and api.dispose() closes it when all tests in the worker are done.

A test asks for it like any other fixture: async ({ page, productCount }) => { ... }.

A worker fixture can only use other worker fixtures, like playwright or browser.

It cannot use page, because a new page is made for each test.


Automatic and Option Fixtures

An automatic fixture runs for every test, even if no test asks for it.

Set auto: true.

This one prints every JavaScript error the page throws:

Example

logErrors: [async ({ page }, use) => {
  page.on('pageerror', error => console.log('Page error:', error.message));
  await use();
}, { auto: true }],

It gives no value to the test, so it calls use() with nothing.

An option fixture is a value that a test file, a describe block or a project can change.

Set option: true, and change it with test.use():

Example

username: ['student', { option: true }],

Example

test.describe('another user', () => {
  test.use({ username: 'teacher' });

  test('option fixture', async ({ username }) => {
    expect(username).toBe('teacher');
  });
});

You can also set option fixtures for a whole project, in the use section of the config file.



Free account

Track your progress

XP earned 0 Day streak 0 Spaces 0 League —

New

Learn in Adventure Mode W3Schools Adventure App

Coding fundamentals as bite-sized lessons and challenges.

×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
sales@w3schools.com

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
help@w3schools.com

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookies and privacy policy.

Copyright 1999-2026 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.