How to use environment variables in Playwright Scripts - Cody Antunez

Environment variables make it easy to share variables between tests.

USERNAME=username
PASSWORD=password
BASE_URL=https://www.dsteele.net

Handling Potentially Undefined Parameters

When getting this error

Argument of type 'string | undefined' is not assignable to parameter of type 'string'.
Type 'undefined' is not assignable to type 'string'.

This means that the parameter could potentially be undefined.

To handle this, there are two options:

  1. Set the parameters ahead of time and throw an error if not present

    const baseUrl = process.env.BASE_URL;
        const username = process.env.USERNAME;
        const password = process.env.PASSWORD;
    
        if (!baseUrl || !username || !password) {
            throw new Error('Missing environment variables');
        }
    
  2. Use a non-null assertion operator

    await page.goto(process.env.BASE_URL!);
    await emailField.fill(process.env.USERNAME!);
    await passwordField.fill(process.env.PASSWORD!);
    

The first approach makes sure the variables are actually available. The second approach is more concise.