I am noticing weird behavior with jest and object destructuring
I have three files
main.js main.spec.js and utils.js
main.spec.js
const utils = require('./utils')
const main = require('./main')
test('example1', () => {
const spy = jest.spyOn(utils, 'myUtil')
main.handler(1)
expect(spy).toHaveBeenCalledWith(1)
})
main.js
const utils = require('./utils')
exports.handler = (option) => {
if (option === 1) {
utils.myUtil(1)
} else {
utils.myUtil(2)
}
}
utils.js
exports.myUtil = (input) => {
console.log(input)
}
The above works fine. However on a minimal change to main.js, destructing myUtil and calling it fails the test.
this is the broken main.js (which is logically identical)
const { myUtil } = require('./utils')
exports.handler = (option) => {
if (option === 1) {
myUtil(1)
} else {
myUtil(2)
}
}
Can anyone explains why?
Assuming I am only writing the test file and would like to not change main file implementation. How can I spy on a destructed object function?