Is there a way to test env
before all tests and not to proceed if an env
is undefined
. I initially tried to define my dotenv
in package.json:
"jest": {
"verbose": true,
"testEnvironment": "node",
"roots": [
"__tests__",
"bin",
"src"
],
"setupFiles": [
"<rootDir>/__tests__/env-setup.js"
],
"modulePathIgnorePatterns": [
"<rootDir>/docs",
"<rootDir>/__tests__/files",
"<rootDir>/__tests__/helpers",
"<rootDir>/__tests__/env-setup"
]
},
and after reading Test process.env with Jest but that didn't work so wrote my test as:
file /__tests__/env.test.js
:
import dotenv from 'dotenv'
dotenv.config()
const envObj = {
foo: process.env.FOO,
bar: process.env.BAR,
}
describe('env tests', () => {
Object.keys(envObj).map((k, i) => {
it(`testing ${Object.keys(envObj)[i]}`, () => {
expect(envObj[k]).toBeDefined()
if (envObj[k] === undefined) new Error(`Missing env variable for "${Object.keys(envObj)[i]}"`)
})
})
})
and while this will error out after the test is still proceeds with all tests. After my research I did find beforeAll
and wrote:
file /__tests__/env.index.js
:
import dotenv from 'dotenv'
dotenv.config()
const envObj = {
foo: process.env.FOO,
bar: process.env.BAR,
}
beforeAll(() => {
return new Promise((res, rej) => {
Object.keys(envObj).map((k, i) => {
if (envObj[k] === undefined)
rej(new Error(`Missing env variable for "${Object.keys(envObj)[i]}"`))
})
res()
})
})
but then my issue is this has to be before every file and it still runs further tests. Further research to see if this has been asked I've read through:
- how to reset module imported between tests
- How do I mock
.env
variables in Jest? - Using .env files for unit testing with jest
- How can I mock a env.dev.js file using Jest?
- set env variable when Running jest
- Jest test not reading environment variables with dotenv
- Environment variables undefined in NextJS when running Jest
- Using environment variables in Node and Jest
In Jest is there a way to run an env test before all tests and the first instance a variable is undefined
it will stop any further tests?