» npm install jest-environment-node
Videos
» npm install jest-environment-node-single-context
The way I did it can be found in this Stack Overflow question.
It is important to use resetModules before each test and then dynamically import the module inside the test:
describe('environmental variables', () => {
const OLD_ENV = process.env;
beforeEach(() => {
jest.resetModules() // Most important - it clears the cache
process.env = { ...OLD_ENV }; // Make a copy
});
afterAll(() => {
process.env = OLD_ENV; // Restore old environment
});
test('will receive process.env variables', () => {
// Set the variables
process.env.NODE_ENV = 'dev';
process.env.PROXY_PREFIX = '/new-prefix/';
process.env.API_URL = 'https://new-api.com/';
process.env.APP_PORT = '7080';
process.env.USE_PROXY = 'false';
const testedModule = require('../../config/env').default
// ... actual testing
});
});
If you look for a way to load environment values before running the Jest look for the answer below. You should use setupFiles for that.
Jest's setupFiles is the proper way to handle this, and you need not install dotenv, nor use an .env file at all, to make it work.
jest.config.js:
module.exports = {
setupFiles: ["<rootDir>/.jest/setEnvVars.js"]
};
.jest/setEnvVars.js:
process.env.MY_CUSTOM_TEST_ENV_VAR = 'foo'
That's it.
Jest automatically defines environment variable NODE_ENV as test(see https://jestjs.io/docs/environment-variables), as you can confirm from your error message:
console.error node_modules/config/lib/config.js:1727
WARNING: NODE_ENV value of 'test' did not match any deployment config file names.
What you can do is simply create config/test.json and include the contents {}, which is an empty valid JSON object.
See https://github.com/lorenwest/node-config/wiki/Strict-Mode
Note: the aforementioned error occurs when you use the config package, and meanwhile you don't have the test.json file in the config directory.
The easiest way is using cross-env package:
npm install --save-dev cross-env
Then, you can use it in your package.json:
"scripts": {
"test": "cross-env NODE_ENV=development jest --config jest.config.json"
}