This is a bit hairy, so bare with me for a second :) Our Jest environment, custom-env
, require
s a module A and sets adds a function to the global scope using this.global.getBar = A.getBar
.
The custom environment is used by a test. This test has a dependency to another module B, which is mocked out using jest.mock('../../moduleB', () => require('./FakeModuleB'))
. FakeModuleB
is using the methods on module A.
Module A looks like this:
const bar = generateUuid();
module.exports = { getBar(){ return bar; } }
The weird thing here is that what is returned by getBar()
differs depending on whether or not it is loaded through jest.mock()
or loaded by the Jest environment. Essentially, jest.mock()
seems to have cleared the loading cache somehow, so it loads the module afresh, which makes me end up with two instances of the module.
I am wondering what the "right" way of handling this could be?
The hackish way is of course to realize what this is and expose a reference to the loaded module on the global scope and refer to that in the require calls in ./FakeModuleB
(which is loaded by jest.mock()
):
// import { getBar } from '../../A'
const { getBar } = global.aModule;
I have then also exposed them in the jest env setup()
method:
const { getBar } = aModule
this.global.aModule = aModule
this.global.getBar = getBar
Of course, I do not like this approach, polluting the global namespace for the sake of hacking around loader issues, but I am not sure how to approach this in another way.