If you use Jest as your trusty testing framework for your Node.js application, you probably ended up in the situation where the code you are trying to test, uses environmental variables that you access with process.env
.
The simplest way to do is to create a file, to be called setEnvVars.js
, and to populate it with the env variables you need, for example:
// .jest/setEnvVars.js
process.env.SOME_VAR = 'something';
process.env.SECRET = 'shh-do-not-tell-to-anyone';
// etc...
What I consider a good practice is also to place this file under a .jest
folder, so we know that everything inside that, is related to Jest.
And just to make it more clear, you should have a file structure similar to this:
|-- .jest
| `-- setEnvVars.js
|-- jest.config.js
|-- package-lock.json
|-- package.json
|-- server.js
Now the next thing to set up is to update your jest.config.js
and tell it to use that file:
// jest.config.js
module.exports = {
setupFiles: ['<rootDir>/.jest/setEnvVars.js'],
// ... other configurations
};
And that's it! Now when you will run the tests, the code will able to access to those mock environmental variables.
Top comments (6)
Nope
I found the solution with setupFilesAfterEnv:
// package.json
{
"name": "...",
"version": "1.0.0",
"description": "...",
"main": "index.js",
"scripts": {
...
"test": "jest"
},
...
"jest": {
"verbose": true,
"silent": false,
"setupFilesAfterEnv": [
"./.jest/setEnvVars.js"
]
}
}
Hi Alesso,
Please, maybe you can help me,
how do you set this setEnvVars.js in package.json config?
// package.json
{
"name": "...",
"version": "1.0.0",
"description": "...",
"main": "index.js",
"scripts": {
...
"test": "jest",
"test:cov": "jest --coverage ",
"test:watch": "jest --watch"
},
"repository": {
...
},
"keywords": [],
"author": "Jakeline Campos",
"license": "MIT",
"dependencies": {
...
},
"devDependencies": {
...
},
"jest": {
"verbose": true,
"silent": false,
"setupFiles": [
".jest/setEnvVars.js"
]
}
}
this not working for me.
here more docs you can read from
it should work like that, but I would recommend to separate the jest configuration in another file as it makes it more readable instead of a very long package.json
I am getting the error:
TypeError: setEnvVars.js: Property left of AssignmentExpression expected node to be of a type ["LVal","OptionalMemberExpression"] but instead got "StringLiteral"
I just copied and pasted the content of your setEnvVars.js file and changed the env to mines.
I am using babel and react-native-dotenv to get the variables from my .env file and this is working on the main app.