Rayrun

How do I parameterize tests and pass environment variables in Playwright?

Answer

Parameterizing Tests and Passing Environment Variables in Playwright

To parameterize tests and pass environment variables in Playwright, you can use the following methods:

1. Import Test Data from CSV

Create a CSV file containing your test data and import it into your TypeScript file using a CSV library. Pass the data as variables when running your tests. Here's an example:

import { test } from '@playwright/test';
import { readFileSync } from 'fs';
import { parse } from 'csv-parse/lib/sync';

const csvData = readFileSync('test-data.csv', 'utf8');
const testData = parse(csvData, { columns: true });

test.describe('Data-driven tests', () => {
  testData.forEach((data) => {
    test(`Test with data: ${JSON.stringify(data)}`, async ({ page }) => {
      await page.goto('https://ray.run/');
      // Use data in your test
    });
  });
});

2. Use Environment Variables

Set environment variables in the command line or .env files, and access them within your tests using process.env. For example:

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

test('Test with environment variables', async ({ page }) => {
  const username = process.env.USERNAME;
  const password = process.env.PASSWORD;
  await page.goto('https://ray.run/');
  // Use username and password in your test
});

3. Set Global Environment Variables

Make arbitrary data available in your tests from your global setup file by setting them as environment variables via process.env. Tests have access to the process.env properties set in the global setup.

4. Parameterize Projects and Fixtures

Define options that can be overridden at runtime via configuration files or command-line arguments using TypeScript or JavaScript code. For example, you can create a custom fixture that accepts parameters:

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

test('Test with custom fixture', async ({ page, customData }) => {
  await page.goto('https://ray.run/');
  // Use customData in your test
});

By using these methods, you can easily parameterize tests and pass environment variables in your Playwright tests.

Thank you!
Was this helpful?
Still have questions?

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

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].