Following on from my post on configuring Cypress to be able to test multiple environments, here’s how I did the same thing in playwright (the node
version)
As before, my “Use Case” is I have some number of defined environments in Kubernetes Clusters ( live
, qa
, dev
), plus some number of personal developer environments…. and I don’t want those personal configs getting put into the repo (developers may want to use personal login details, for example)
The solution that worked for me is essentially the same as the Cypress idea: there are multiple config files, and some environment variable is used. In this case, I’m “hacking” the idea of .env
to my benefit.
The whole idea of dotenv
is that there’s an external file that loads a bunch of values into process.env
for us … and note that dotenv
can specify the path to the file being loaded. As with the Cypress example, we use an environment variable to select the one we want to use.
The “magic” happens in the central playwright.config.ts
file:
//playwrite.config.ts
import { defineConfig, devices } from '@playwright/test';
import * as dotenv from 'dotenv';
// import the right config - default to beta, change using a `CONTEXT` env variable
let context:string;
if (process.env.CONTEXT == null) {
context = 'beta'
} else {
context = process.env.CONTEXT;
}
dotenv.config({ path: `myConfigs/env-${context}` });
export default defineConfig({
.....
});
… and we place the various config files in, you guessed it, a directory called myConfigs
– and name each file env-foo
base_url=https://example.com
something=something_else
ad=nausium
In the tests, we then have something akin to:
import { test, expect } from '@playwright/test';
const baseUrl = process.env.base_url ?? "https://example.com";
const something = process.env.something ?? "";
test.describe('Test something', () => {
....
});
To select the appropriate config file, run:
CONTEXT=live npx playwright test
where the value of CONTEXT
matches the identifier of the config file.