Rayrun
← Back to Discord Forum

playwright using the old values in dotenv file in the test

Hi there!

Hope someone can help me.

I have a global setup via project dependencies that get an email address from certain url then save it in the .env file so it can be called by the other tests. This is done using search and replace in the .env file by calling a node script in my global setup.

This works fine. I can see that my email variable gets updated after the globalsetup.ts finished running. However, when the next test/spec.ts run and tried to access the email variable in .env file, it is not using the updated email and instead using the previous email before it got updated to a new one.

I assume that the .env was read and put into memory when it run and it is using the email variable in the memory instead of the new email in the .env file.

Do you know a way to tell playwright to reread the .env file to get the new email variable?

Or can you suggest a way to do it differently but same result?

Basically, i want to use a global variable that is acquired by global setup that I can call from all my tests/spec.ts files.

Thank you in advance.

This thread is trying to answer question "How can I get Playwright to reread the .env file for an updated email variable, or is there an alternative way to achieve this?"

0 replies

Answer

Updating Environment Variables in Playwright

First, create a .env file in your project directory and set your email variable, like so: [email protected].

Next, in your playwright.config.ts file, import and configure the dotenv package to read the .env file:

import dotenv from 'dotenv';
import path from 'path';

dotenv.config();
dotenv.config({ path: path.resolve(__dirname, '..', '.env') });

In your configuration options, you can now access your environment variables using process.env:

export default defineConfig({
  use: {
    baseURL:
      process.env.STAGING === '1'
        ? 'http://staging.ray.run/'
        : 'http://ray.run/',
    email: process.env.EMAIL,
  },
});

When you run your tests with npx playwright test, Playwright will use the updated values from the .env file.

Alternatively, you can set environment variables directly in your command line:

[email protected] npx playwright test

This will override the .env file. Playwright provides multiple ways to set and update environment variables, so choose the method that suits your needs best.

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