Test cannot change process environment
See original GitHub issue🐛 Bug Report
It is not possible for a test to set the process environment as node_modules/jest-util/build/installCommonGlobals.js runs node_modules/jest-util/build/createProcessObject.js createProcessEnv() which replaces the real process.env with a fake one. This means that tests cannot communicate with binary/native modules via the environment.
My specific use case is, in a nodejs jest test, a need to set KRB5_CONFIG in the real process environment prior to interacting with the native library MIT krb5 via https://www.npmjs.com/package/gssapi.js.
To Reproduce
Rather than my use case, which requires a third-party binary node module, I will just provide a repro case that uses standard node modules. This example require a system with a bash shell, where it will write output: bar
to standard output.
const child = require("child_process");
process.env.foo = "bar";
child.exec("echo -n $foo", (err, stdout, stderr) => {
console.log(`output: ${stdout}`);
});
If this code is instead moved into a jest test it will just write output:
to standard output as the foo variable will only have been set in the jest fake process.env, not in the real (OS level) process environment, so it is not inherited by the process that we start.
In this repro case you can of course just pass the env explicitly as an option to child_process.exec(), but that is besides the point. The point is that process.env changes do not update the real system/OS-level process environment, which prevents communication via the process environment to binary modules.
Issue Analytics
- State:
- Created 4 years ago
- Comments:5 (1 by maintainers)
Top GitHub Comments
The problem is
Date
only reading the default from env (AFAIK). Unfortunately, I think that’ll only be fixed byTemporal
: https://tc39.es/proposal-temporal/docs/#Temporal-TimeZone.If you’re stuck with legacy
Date
, what you could do is write a custom test environment that sent the realprocess.env
through. You’d then opt out of the test isolation, but that might be a tradeoff that’s worth it to you.Another option is to create a test env that allows you to set timezone through config. Jest 28 (currently in alpha) allows you to set config per test file via docblock.
Running that prints
Note that these tests should then run sequentially since they both mutate the same global process environment
This issue has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs. Please note this issue tracker is not a help forum. We recommend using StackOverflow or our discord channel for questions.