Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Skipping env var validation in tests #209

Open
hsuabina opened this issue Apr 11, 2023 · 1 comment
Open

Skipping env var validation in tests #209

hsuabina opened this issue Apr 11, 2023 · 1 comment

Comments

@hsuabina
Copy link

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!

@hsuabina
Copy link
Author

hsuabina commented Apr 11, 2023

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().

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant