2

I have read and tried the options described in every stackoverflow thread related to this issue but I'm tempted to believe they're all out of date and no longer reflect jest behaviour.

I have a configuration service which returns a default value or a value from the environment.

During tests, I need to overwrite process.env values such as:

        process.env.config_CORS_ENABLED = overwrittenAllConfig;
        // expecting them to be overwritten
        const corsEnabled = allConfigs.get('CORS_ENABLED');
        expect(corsEnabled).toStrictEqual(overwrittenAllConfig);

Everything works fine on windows but on WSL and linux workers during pipelines, the value from the environment is never set.

I have beforeEach and afterEach hooks:

    afterEach(async () => {
        process.env = env;
    });
    beforeEach(async () => {
        jest.resetModules();
        process.env = { ...env };

and at the beginning of the describe block:

    const env = process.env;

I have also tried the Object.assign() strategy for the whole process.env object but that didn't work either, and upon logging the process.env object after assigning it has a ton of values unrelated to what I've assigned to it.

I've also tried the --runInBand and the --maxWorkers 1 option to make sure that there aren't conflicts, but that didn't do anything.

I can't be setting up env variables using .dotEnv() as I need to assign multiple different values between expectations in some cases.

This is a very reasonable real-world usage and I'm just shocked at the mountain of issues I've had trying to get this working so far.

Happy to try any suggestions. An unreasoanble amount of time has already been spent reading threads and blogs and documentation attempting to get this working.

SebastianG
  • 8,563
  • 8
  • 47
  • 111

1 Answers1

0

Dynamic imports might be the answer, as described in Dynamically import module in TypeScript.

When you import the module to be tested (allConfigs) at the top of the file, it will import process before you've intercepted it. Therefore remove that import at the top, and do something like this:

const allConfigs = await import('<correctPath>/allConfigs');
const corsEnabled = allConfigs.get('CORS_ENABLED');

Please note that dynamic imports require an await, so you'll need to mark your test with async.

sfuqua
  • 5,797
  • 1
  • 32
  • 33