I have a Jest test setup to test APIs (using supertest), which leads to an error on account of API being tested not being able to read the variables in an .env file.
But when I test the same API thorough Postman, it works fine and I can see the variables are loaded correctly in the console.
So, essentially the same code works differently (can read .env file in one case and not in the other) when tested through Jest and when tested manually through Postman. What could be reason for this?
I'm loading the .env file via the CLI option. That is: 'node -r dotenv/config index.js".
[Feature]: Allow `@jest-environment` pragma to be below other comments
node.js - Using environment variables in Node and Jest - Stack Overflow
@jest-environment jsdom not working
jestjs - Set custom Jest environment in docblock - Stack Overflow
Videos
» npm install jest-environment-node
Make sure you have both packages jest and jest-environment-jsdom installed in the same version. The latter is required to be installed separately from jest version 28 on. I ran into the same issue when downgrading jest to 27.x but not jest-environment-jsdom. Have a look at the version 27 to 28 upgrade guide about using JSDOM test environment.
I had different versions of local jest and global jest, jest-environment-jsdom was not installed globally. This caused me the issues. Running it locally via
./node_modules/jest/bin/jest.js src/my-test.spec.ts
or updating global jest packages did the job for me. I see that this is mentioned in one of the comments above, but somehow I missed it and spent too much time on it so posting it here
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"
}