Thursday, May 1, 2025

How to pass environment variables in Playwright

 In this example we will explore how to set access environment variables in Playwright using CLI. To pass environment variables in Playwright tests, the approach varies slightly across Windows, macOS, and Unix/Linux. 

How to pass environment variables in Playwright

Here's a quick reference for each:


Windows CMD

In Windows Command Prompt (cmd.exe), use the set command with &&:

set BASE_URL=https://staging.example.com && npx playwright test


Multiple variables:

set VAR1=value1 && set VAR2=value2 && npx playwright test

Windows PowerShell

Use $env: syntax:
$env:BASE_URL = "https://staging.example.com"
npx playwright test


Multiple variables:

$env:BASE_URL = "https://staging.example.com"
$env:API_KEY = "mykey"
npx playwright test


Unix/Linux/macOS

You can pass environment variables inline before the command:

BASE_URL=https://staging.example.com API_KEY=mykey npx playwright test

Multiple variables:

ENV1=value1 ENV2=value2 npx playwright test

NOTE : This works in most Unix-like terminals (Bash, Zsh, etc.)


Example -1

You can use environment variables to configure tests from the command line.

For example, consider the following test file that needs a username and a password. It is usually a good idea not to store your secrets in the source code, so we'll need a way to pass secrets from outside.

example.spec.ts

test(`example test`, async ({ page }) => {
  // ...
  await page.getByLabel('User Name').fill(process.env.USER_NAME);
  await page.getByLabel('Password').fill(process.env.PASSWORD);
});

You can run this test with your secret username and password set in the command line.

USER_NAME=me PASSWORD=secret npx playwright test


Example -2

Similarly, configuration file can also read environment variables passed through the command line.

playwright.config.ts

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

export default defineConfig({
  use: {
    baseURL: process.env.STAGING === '1' ? 'http://staging.example.test/' : 'http://example.test/',
  }
});

Now, you can run tests against a staging or a production environment:

STAGING=1 npx playwright test


This is all about accessing and passing environment variables in playwright.


 

No comments:

Post a Comment