What is the process of using and creating fixtures in Playwright Test?


Using and Creating Fixtures in Playwright Test

Test fixtures in Playwright help set up an environment for each test. Playwright Test offers built-in fixtures like page, context, browser, browserName and request APIRequestContext.

Here's how you can use a fixture in your tests:

import {test} from '@playwright/test';
test('basic test', async ({page}) => {
  await page.goto('https://ray.run/');
  await expect(page).toHaveTitle(/Ray/);

In this example, we're using the page fixture to set up an isolated page for our test run.

You can also create custom fixtures with .extend(). Here's an example:

const slowFixture = base.extend<{slowFixture: string}>({
  slowFixture: [async({}, use) => {
    // perform a slow operation
    await use('hello');
  }, {timeout: 60000}]

In this code, we're creating a custom fixture called slowFixture.

Playwright Test also supports worker-scoped fixtures. These are set up for each worker process. Here's how to create one:

export const myTest = base.extend<{}, {account: Account}>({
  account: [async({browser}, use) => {
    const username = 'user' + workerInfo.workerIndex;
    const password = 'verysecure';
    // perform some operations
    await someOperation();
    return {username,password};
   }, {scope:'worker'}]

In this example, we're creating a worker-scoped fixture called account.

Thank you!
Was this helpful?
Still have questions?

If you still have questions, please ask a question and I will try to answer it.

Related Questions

AboutQuestionsDiscord ForumBrowser ExtensionTagsQA Jobs

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 luc@ray.run.