Lately, I been working a lot with JavaScript and Node.js, one thing I struggled is setting up environment variables so I could run my automation tests based on the flag I passed. As a test runner I mostly use Mochajs, so my initial thought Mocha should have some hooks to pass env variable as a parameter. And I was not wrong, there is a guide HOW-TO: use environment variables . Well, if you smart enough you would probably figure this out. But I struggled to understand how to set those variables.
Later in my research I discovered process.env actually part of Node.js API it became more clear that I have to get .env file where all my variables will be set, here is sample code:
// .env file
APP_DEV = 'your_dev_env_url_here'
APP_PREPROD = 'your_preprod_env_url_here'
Ok now we set everything up let’s make sure right variable selected when we pass our parameter in the command line:
// your_test.spec.js file
require('dotenv').config()
let env
if (process.env.CI === "DEV"){
env = `${process.env.APP_DEV}`
}else if(process.env.CI === "PREPROD"){
env = `${process.env.APP_PREPROD}`
}
Noticed something? Yeah, require('dotenv').config()
is the key here, we have to install dotenv node library in order to call those variables from .env file. Let’s run npm install dotenv
and get the library to our package.json file.
Now how do I run the tests, well you could either pass the parameter in the terminal, like so: env CI=DEV npm test
, where test is defined script in our package.json file
"scripts": {
"test": "./node_modules/mocha/bin/mocha --timeout=30000 ./tests"
},
Or we could just path same parameter inside the test script:
"scripts": {
"test": "env CI=DEV ./node_modules/mocha/bin/mocha --timeout=30000 ./tests"
},
Then we could just run the script file: npm test
It is totally up to you how to configure your test environments, coming from pytest (Python testing library) I prefer to pass it through the command line. And if you want to learn more, here is a good youtube video I found while searching for solution Configuring Environment Variables in Node.js (all credits to Code Realm).
Hope you learned something new today, feel free to post your ideas and questions in comments.