Creating a fixture in Playwright is a breeze with the extend
method from the @playwright/test
package. Fixtures are handy for setting up and tearing down resources for tests, like browser instances or pages.
You can specify the scope of your fixture. Test-scoped fixtures are set up and torn down for each test, while worker-scoped fixtures are shared across multiple tests within a single worker process. You can even define dependencies between fixtures with the dependsOn
option.
To create a fixture, define an async function that returns the resource for your tests. This function receives an object with properties depending on your fixture's scope (e.g., page
, context
, or browser
). You can use this resource in your test by passing it as an argument.
Here's an example of a fixture that sets up a new page instance before each test:
import { test as base } from '@playwright/test';
const myFixture = base.extend({
page: async ({ browser }, use) => {
const page = await browser.newPage();
await use(page);
await page.close();
},
});
test('my test', async ({ page }) => {
// Use the "page" instance here
});
You can define options for your fixtures using TypeScript interfaces. Options allow you to configure your fixtures externally (e.g., via command-line arguments or configuration files). To do so, extend your fixture type with an interface containing all of its options:
import { FixtureFn } from '@playwright/test';
interface MyOptions {
foo: string;
}
const myFixture: FixtureFn<MyOptions> = base.extend({
bar: async ({ foo }, use) => {
console.log(`Using option "foo": ${foo}`);
await use('hello');
},
});
test('my test', async ({ bar }) => {
// Use "bar" here
});
That's it! You're now ready to create your own fixtures in Playwright. Happy testing!
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].