fotoflo
fotoflo

Reputation: 957

using .env.local with playwright

I'm setting up some first playwright tests for my nextjs project. I already have environment variables in my .env.local and I'd like to pull them into my test env.

I'm looking at the documentation and I see that I can add require("dotenv").config(); to my playwright.config.js but nothing is happening when I do that (the scripts are erroring out because of undefined.

I tried both calling process.env.foo directly within the script, and also adding a use: {foo: process.env.FOO} clause to the playwright.config.js and moving my variables to .env file instead of .env.local but nothing worked.

Help would be much appreciated! thank you.

Upvotes: 3

Views: 8825

Answers (2)

mmik
mmik

Reputation: 5981

npm install @next/env

Next.js has a first party @next/env package that can be used in the playwright.config.ts file to ensure Playwright knows about the desired environment.

import { loadEnvConfig } from "@next/env";

loadEnvConfig(process.cwd());

Upvotes: 0

fotoflo
fotoflo

Reputation: 957

After reading using dotenv path with JEST I found the solution is to configure the require statement:

  1. install the dotenv package (the one that comes with next.js isn't loaded)
npm install --save-dev dotenv
  1. In .env.local - set the vars
FOO=bar
  1. In playwright.config.js - set which env file to use
require("dotenv").config({ path: "./.env.local" });
console.log(process.env.FOO); // prints "bar"

  1. In a spec
test("env", async ({ page }) => {
  console.log(process.env.FOO); // also prints "bar"
})

Upvotes: 8

Related Questions