mfncooper / mockery

Simplifying the use of mocks with Node.js
Other
1.1k stars 60 forks source link

Destructuring Bug or am I doing this wrong? #65

Open JemiloII opened 7 years ago

JemiloII commented 7 years ago

Just trying to use some destructing.

If I have.

// add.js
const {a, b} = require('./numbers.js');

const add = () => a + b;

module.exports = {add};

The test fails when I go to mock numbers. However, if I rewrite the module to not have destructuring...

const numbers = require('./numbers.js');

const add = () => numbers.a + numbers.b;

module.exports = {add};

My test will pass. It's kinda annoying actually. Is there anything I can do about this? I thought the mockery was suppose to overwrite the require. Or is mockery simply just passing the object around and with destructuring, new objects are created rather than references?

laggingreflex commented 6 years ago
const {a, b} = require('./numbers.js');
const add = () => a + b;

Here a and b are evaluated right away and thus cannot be changed when you mock require('./numbers.js')

const numbers = require('./numbers.js');
const add = () => numbers.a + numbers.b;

Whereas here numbers.a and numbers.b aren't evaluated until you call add(), therefore mocking numbers work in this case.

This would also not work for the same reason:

const numbers = require('./numbers.js');
const a = numbers.a
const b = numbers.b
const add = () => a + b;
JemiloII commented 6 years ago

Ahhh, okay thanks for the clarification!