jhnns / rewire

Easy monkey-patching for node.js unit tests
MIT License
3.08k stars 128 forks source link

Special handling for process.env? #205

Closed dhensby closed 1 year ago

dhensby commented 2 years ago

When trying to set process.env values with rewire the revert attempts to roll-back the changes by setting process.env[var] = undefined. However, Node seems to perform a toString() manipulation on any value set on the .env props meaning that this turns a previously undefined environment variable into "undefined".

eg:


const revert = rewiredModule.__set__({
  'process.env.MY_ENV': 'my value',
});

revert();

// process.env.MY_ENV is now "undefined"

Would it be prudent to manually handle environment variables, either by manually running delete process.env[name] on any assignments the library sees or (a bit more lazy approach) automatically reset the env vars on every revert.

ie: every __set__ call caches the env vars values at that time and just pushes a special assignment in the revert?

jhnns commented 1 year ago

Damn, that sucks. Didn't know Node does this :)

Assignments to properties using the dot notation are discouraged (as noted in the caveats section) as they mutate the actual process object (you could alternatively just override process.env in your test).

Does it work for you if you call __set__ like this?

const revert = rewiredModule.__set__({
  process: {
    ...process,
    env: {
      ...process.env,
     MY_ENV: "my value"
    }
  }
});
dhensby commented 1 year ago

I hadn't read the caveats, so hadn't seen that recommendation 🤦‍♂️

That is essentially how I modify the env object now, so if that's the right approach, then we can just close this. Cheers.