Rayrun

What is the method to parameterize tests in JavaScript using Playwright Test?

Answer

Creating Parameterized Tests with Playwright

With Playwright Test, you can easily create parameterized tests in JavaScript.

Test Level Parameterization

First, you can define an array of parameters and loop over them. Here's an example:

const people = ['Alice', 'Bob'];
for (const name of people) {
  test(`testing with ${name}`, async () => {
    // ... your test code here
  });
}

This will generate multiple tests, each with a different parameter value.

Project Level Parameterization

You can also define options for your tests using the extend function from Playwright Test.

import { test as base } from '@playwright/test';

export type TestOptions = {
  person: string;
};

export const test = base.extend<TestOptions>({
  person: ['John', { option: true }],
});

test('test 1', async ({ page, person }) => {
  // ... your test code here
});

In this example, the person option is defined with a default value of "John". You can override this value in the configuration file or when running the tests.

Using Fixtures with Options

You can use fixtures with options to further customize your tests. Fixtures let you set up reusable state or perform common actions before each test.

import { test as base } from '@playwright/test';

export type TestOptions = {
  person: string;
};

export const test = base.extend<TestOptions>({
  person: ['John', { option: true }],
  
  page: async ({ page, person }, use) => {
    await page.goto('https://ray.run/chat');
    await page.getByLabel('User Name').fill(person);
    await page.getByText('Enter chat room').click();
    await use(page);
  },
});

test('test 1', async ({ page, person }) => {
  // ... your test code here
});

In this example, the page fixture is overridden to include the person parameter as a "name" for the chat room. Each test will receive a pre-configured page with the person's name already filled in.

By using Playwright Test's parameterization and fixture capabilities, you can create a template for similar tests in JavaScript that takes multiple parameters. This allows you to easily generate and customize tests based on different input values or configurations.

References

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 Discord Threads

Related Questions

TwitterGitHubLinkedIn
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 [email protected].