Open luca-gr4vy opened 2 months ago
Solved by using a separate file to export all the env variables and reassign / mock inline, for example:
// env.js
export const env = {
REACT_APP_FEATURE: import.meta.env.REACT_APP_FEATURE
}
import { env } from './env'
test('should return true if feature is enabled', () => {
env.REACT_APP_FEATURE = 'true'
expect(hasFeature()).toBe(true)
})
test('should return false if feature is not enabled', () => {
env.REACT_APP_FEATURE = 'false'
expect(hasFeature()).toBe(false)
})
It's a bit of a workaround, but fine in my case
Unfortunately, since environment variables are statically replaced during compilation (with compile-time mode), they cannot be changed after a compile-time transformation.
If you're still in the early stages of integrating import-meta-env, maybe you can try another package: https://github.com/runtime-env/runtime-env
Here is an example based on https://github.com/runtime-env/runtime-env/tree/main/examples/test folder:
.runtimeenvschema.json
{
"type": "object",
"properties": {
"HAS_FEATURE": {
"type": "boolean"
}
},
"required": ["HAS_FEATURE"]
}
.env
HAS_FEATURE=true
src/index.js
module.exports = function hasFeature() {
return globalThis.runtimeEnv.HAS_FEATURE;
};
__tests__/index.test.js
const hasFeature = require("../src");
test("true", () => {
globalThis.runtimeEnv.HAS_FEATURE = true;
expect(hasFeature()).toBe(true);
});
test("false", () => {
globalThis.runtimeEnv.HAS_FEATURE = false;
expect(hasFeature()).toBe(false);
});
Is there a way to reassign environment variables in a Jest test?
I'm using CRA v5 with
@import-meta-env/babel
, craco (not having to eject the app) and the babel transform function from https://github.com/runtime-env/import-meta-env/blob/a356a958f5e1e9f11d8852d424a6f2b37abc736e/packages/examples/create-react-app-example/config/jest/babelTransform.jsFor example:
with a test:
The error I'm getting is:
I could do that with
process.env
and it worked fine.Vitest has
stubEnv
(https://vitest.dev/api/vi#vi-stubenv), looking for similar functionality