To create and access a page fixture in a beforeEach
hook using @playwright/test, you can define a custom fixture using the test.fixtures()
method. Here's how you can do it:
import { test } from '@playwright/test';
test.fixtures({
page: async ({ browser }, use) => {
const page = await browser.newPage();
await use(page);
await page.close();
},
});
This code defines a page
fixture that creates a new isolated page for each test run using browser.newPage()
. The use
callback function is called with the created page
instance, signaling that it's ready for use in tests.
To access the page
fixture within a test, include { page }
as an argument:
import { test } from '@playwright/test';
test('my test', async ({ page }) => {
// Use the 'page' instance here.
});
When you run your tests with the Playwright Test runner (npx playwright test
), it will automatically set up the required fixtures before executing the tests.
By defining fixtures in @playwright/test, you can easily set up resources like pages or contexts for each test without worrying about cleanup or isolation. This makes your tests more efficient and easier to maintain over time.
If you still have questions, please ask a question and I will try to answer it.
Rayrun is a community for QA engineers. I am constantly looking for new ways to add value to people learning Playwright and other browser automation frameworks. If you have feedback, email [email protected].