I am trying to run a mocha unit test but one of the modules used by the module I am testing on requires environment variables such as process.env.CLIENT_ID through dotenv. When I run my Mocha test, these environment variables are not found. How can I can include environment variables from a .env file in my mocha unit tests?
test.js:
var messenger = require(__dirname + "/../routes/messenger.js");
var assert = require("assert")
describe("Return Hello", function(){
it('Should return hello',function(done){
messenger.testFunction(function(value){
assert(value === "Hello", 'Should return Hello')
done()
})
})
})
Section of file that contains the problem that goes through unit test:
var express = require("express")
var router = express.Router();
require('dotenv').config()
var plaid = require('plaid');
var mysql = require('mysql');
var fs = require("fs");
const plaidClient = new plaid.Client(
process.env.PLAID_CLIENT_ID, // these are all not found
process.env.PLAID_SECRET,
process.env.PLAID_PUBLIC_KEY,
plaid.environments.sandbox);
to me the most elegant way of setting your env before the tests is inside package.json.
Here is an example to adapt to your own npm test command:
"scripts": {
"test": "mocha -r dotenv/config"
}
The main idea is to add the -r dotenv/config.
The method works as well with dotenv-flow, do not forget to add NODE_ENV=test at the beginning of the command.
It works as well with nodemon.
I found the solution. I had to link the dotenv config explicitly to the location to the .env file by adding the path:
options of the .config()
method.
Example:
var envPath = __dirname + "/../.env"
require('dotenv').config({path:envPath})
// ^ this was incorrect
var express = require("express")
var router = express.Router();
var plaid = require('plaid');
var mysql = require('mysql');
var fs = require("fs");
const plaidClient = new plaid.Client(
process.env.PLAID_CLIENT_ID,
process.env.PLAID_SECRET,
process.env.PLAID_PUBLIC_KEY,
plaid.environments.sandbox);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With