0

I was trying to test a function using Jest where I need to mock a Webpack-defined global to test all the cases. I was unable to do so.

// webpack.config.js

...
new webpack.DefinePlugin({
__ENV__: `'${process.env.NODE_ENV}'`
}),
...

// commonUtil.js

const log = __ENV__ !== envs.PROD ? console.log.bind(console) : () => {};

// commonUtil.jest.js

describe('commonUtils', () => {
  const test = 'test';

  it('should log to the console in non-production environment', () => {
    __ENV__ = envs.PROD;
    log(test);
  });

 it('should log to the console in non-production environment', () => {
    __ENV__ = envs.DEV;
    log(test);
  });
});
2
  • Assuming that code is at the top level of your module, the condition is evaluated at import time. Changing the value of __ENV__ after that isn't going to change what you've imported into your test.
    – jonrsharpe
    Commented May 17 at 10:35
  • but somehow we should be able to mock it to test this util Commented May 17 at 12:10

0

Browse other questions tagged or ask your own question.