Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

123
Views
jest fails to spy if object is destructed

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?

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!