简体   繁体   中英

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);

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);

The below thing worked for me ;)

"scripts": {
        "test": "DOTENV_CONFIG_PATH=test.env mocha -r dotenv/config ",
      }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM