jupiter / simple-mock

Super simple stubs and spies with 1-step sandbox restore
MIT License
87 stars 12 forks source link

Not working with destructured objects #33

Closed tejohnso closed 3 years ago

tejohnso commented 3 years ago

When using object destructuring on the require object, the mock doesn't work. I'm not sure this is fixable as there is no longer a reference to a mocked object property during test runtime.

Test

const simple = require("simple-mock");
const module = require("module.js");
const target = require("target.js");

simple.mock(module, "functionToBeMocked").returnWith(true);
target.targetFn()

Code Under Test in target.js (NOT working with destructuring on first line)

const {functionToBeMocked} = require("module.js");

function targetFn {
  functionToBeMocked() // calls real functionToBeMocked from module.js instead of returning with true as mocked
}

Code Under Test in target.js (Works without destructuring)

const module = require("module.js");

function targetFn {
  module.functionToBeMocked() // calls real functionToBeMocked from module.js instead of returning with true as mocked
}
jupiter commented 3 years ago

Yes, the destructuring happens at module load time, which is before the mocking happens. Had the destructuring been inside the function, it would happen at run time, which should be after mocking.

tejohnso commented 3 years ago

Yeah. It would be nice to be able to use destructuring at module load time while still being able to mock. But I'll just go ahead and close this :)