Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Environment variables not found during Mocha unit test Node.js

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);
like image 915
s_kirkiles Avatar asked May 06 '17 00:05

s_kirkiles


2 Answers

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.

like image 117
Benjam Avatar answered Oct 05 '22 23:10

Benjam


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);
like image 21
s_kirkiles Avatar answered Oct 06 '22 00:10

s_kirkiles