Reputation: 371
I've got Playwright test written using TypeScript and I would like to use variables from .env in my test file, how can I do that?
Upvotes: 21
Views: 44740
Reputation: 2260
In addition to Max Schmitt's answer, here's 3 other ways to do it:
Add dotenv-cli to your dev dependencies then use it: dotenv playwright test
(or npx dotenv playwright test
if you're running this command outside of a package.json script).
Use the --require
Node.js option and NODE_OPTIONS
to set it: NODE_OPTIONS=--require=dotenv/config playwright test
.
Use the --require
Node.js option and npx to set it: npx --node-options=--require=dotenv/config playwright test
(if you're using an old version of npx, you might need to replace --node-options
by --node-arg
)
Upvotes: 5
Reputation: 351
You can use env-cmd:
// playwright.config.ts
import "dotenv/config";
import { defineConfig, devices } from "@playwright/test";
...
// package.json
{
"scripts": {
...
"test": "env-cmd -f .env.development --no-override playwright test",
"test:staging": "env-cmd -f .env.staging --no-override playwright test",
"test:production": "env-cmd -f .env.production --no-override playwright test"
},
}
In addition:
With env-cmd
, the environment variables can be set in any format like .js
or .json
. Advanced usage details are here.
Add .env-cmdrc
in the root folder. I preferred to use it for test commands only.
{
"development": {
"BASE_URL": "DEV_URL"
},
"staging": {
"BASE_URL": "STAGING_URL"
},
"production": {
"BASE_URL": "PROD_URL"
}
}
In package.json
:
{
"scripts": {
...
"test": "env-cmd --environments development --no-override playwright test",
"test:staging": "env-cmd --environments staging --no-override playwright test",
"test:production": "env-cmd --environments production --no-override playwright test"
},
}
Upvotes: 0
Reputation: 206
Here's an example of how I do it:
// playwright.config.ts
import { PlaywrightTestConfig } from '@playwright/test';
if (process.env.NODE_ENV === 'development'){
require('dotenv').config({path: '.env'});
}
const config: PlaywrightTestConfig = {
// ...
}
Upvotes: 1
Reputation: 3152
You can put require('dotenv').config()
inside your playwright.config.ts
and then it will work, see here:
https://www.npmjs.com/package/dotenv
Upvotes: 16