Rayrun

How can I use environment variables to pass dynamic values in Playwright tests?

Answer

Using Environment Variables in Playwright

You can pass dynamic values in Playwright tests using environment variables. Here's how:

Setting Environment Variables

You can set environment variables in the Playwright configuration file (playwright.config.ts). For example, you can set the baseURL property based on the STAGING environment variable. This allows you to switch between staging and production environments.

module.exports = {
  baseURL: process.env.STAGING ? 'https://staging.ray.run' : 'https://ray.run',
  // ...
};

You can also use .env files to manage environment variables. Create a .env file and define your variables with their values. For example:

STAGING=https://staging.ray.run
USERNAME=testuser
PASSWORD=testpass

Accessing Environment Variables in Tests

To access environment variables in tests, use process.env.VARIABLE_NAME. For example, to fill a "User Name" field based on the USERNAME environment variable, use:

await page.getByLabel('User Name').fill(process.env.USERNAME);

Using Fixtures and Options

Playwright's test-runner allows you to pass dynamic values in tests using fixtures and options. Fixtures let you define reusable setup steps for tests. Options let you customize test behavior. For example, you can define an option called person with a default value of 'John'. This option can be overridden in the configuration file or via command line arguments.

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

test('example test', async ({ page }) => {
  await page.goto('https://ray.run');
  // ...
});

Remember to set the necessary environment variables before running your tests.

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