From 22bc9c02851ea56a48f694e13582ecadfdc1f0d2 Mon Sep 17 00:00:00 2001 From: Mark Skelton Date: Sun, 11 Jul 2021 16:18:37 -0500 Subject: [PATCH] docs(test-advanced.md): Overriding fixtures (#7528) --- docs/src/test-fixtures.md | 60 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) diff --git a/docs/src/test-fixtures.md b/docs/src/test-fixtures.md index 62c5330000..f5ad1355f0 100644 --- a/docs/src/test-fixtures.md +++ b/docs/src/test-fixtures.md @@ -335,3 +335,63 @@ const test = base.extend<{}, ExpressWorkerFixtures>({ export default test; ``` + +## Overriding fixtures + +In addition to creating your own fixtures, you can also override existing fixtures to fit your needs. Consider the following example which overrides the `page` fixture by navigating to a specified URL: + +```js js-flavor=js +const base = require('@playwright/test'); + +exports.test = base.test.extend({ + page: async ({ baseURL, page }, use) => { + await page.goto(baseURL); + await use(page); + }, +}); +``` + +```js js-flavor=ts +import { test as base } from '@playwright/test'; + +export const test = base.extend({ + page: async ({ baseURL, page }, use) => { + await page.goto(baseURL); + await use(page); + }, +}); +``` + +Notice that in this example, the `page` fixture is able to depend on other built in fixtures such as `baseURL`. This allows us to override the `baseURL` used by the `page` fixture in our tests using `test.use`. + +```js js-flavor=js +test.use({ baseURL: 'https://playwright.dev' }) +``` + +```js js-flavor=ts +test.use({ baseURL: 'https://playwright.dev' }) +``` + +Fixtures can also be overridden where the base fixture is completely replaced with something different. For example, we could override the `storageState` fixture to provide our own data. + +```js js-flavor=js +const base = require('@playwright/test'); + +exports.test = base.test.extend({ + storageState: async ({}, use) => { + const cookie = await getAuthCookie(); + await use({ cookies: [cookie] }); + }, +}); +``` + +```js js-flavor=ts +import { test as base } from '@playwright/test'; + +export const test = base.extend({ + storageState: async ({}, use) => { + const cookie = await getAuthCookie(); + await use({ cookies: [cookie] }); + }, +}); +```