Skipping env var validation in tests
I'm trying to find an elegant way to prevent my env vars from being validated when NODE_ENV=test. When we run unit tests (with Jest) we are not injecting any env vars anyhow (I think this is the way it should be). I'm basically saying all env vars should be optional when running tests.
With that in mind, the current working solution I have is this:
import { cleanEnv, str, testOnly } from "envalid";
import * as dotenv from "dotenv";
dotenv.config();
const envValidation = {
ENV_1: str({ default: undefined, devDefault: testOnly(undefined) }),
ENV_2: str({ devDefault: testOnly(undefined) }),
// ...
};
const env = cleanEnv(process.env, envValidation);
export default env;
Since all envs use devDefault: testOnly(undefined) I'm able to effectively skip the env validation when running tests. But it's a bit of an ugly approach, since on some services the number of envs is large and we need to add that default value on every single env var we use.
Is there a better alternative to this approach? I think I could fiddle with a custom reporter (that only throws if NODE_ENV !== 'test') or a custom validator (that always return the sanitized value undefined when NODE_ENV === 'test') but would like to get some thoughts first if possible.
Thanks!
Actually, I don't think this approach works.
When using something like this:
CORS_DOMAINS_REGEX: str({
default: "",
devDefault: testOnly(undefined),
})
I get the following error when a string is expected
some-api:dev: [1] /code/some-api/build/app.js:45
some-api:dev: [1] allowedOriginsCORS.push(new RegExp(env_1["default"].CORS_DOMAINS_REGEX));
TypeError: Cannot convert a Symbol value to a string
The error only goes away if I remove the devDefault key. The issue goes away if I don't use use testOnly().