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

188
Views
jest mock function that returns an object

I have a function that returns a object

function getSettings() {
  return {
    foo: 'bar'
  }
}

And I have a function that uses the function above internally

function myFunction() {
  const { foo } = getSettings()

  return foo
}

And I have a test that I want to change the value of foo

it('', async () => {
  const value = '123'

  const fooObj = {value: '123'}
  jest.spyOn(getSettings, 'foo').mockReturnValue(fooObj )

  const result = myFunction()

  expect(result).toBe(value)
})

enter image description here

But this doesn't work. Any ideia how to mock the return value of getSettings?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

After question edit (attaching the error image) and code update

You cant do jest.spyOn(getSettings, 'foo') you need to put the object/module in the first argument and the second argument should be the function name.

You can test it by changing it to:

const fileWithGetSetting = require('<your-path>');

it('', async () => {
  // the key should be foo and not value
  const fooObj = {foo: '123'}

  jest.spyOn(fileWithGetSetting, 'getSettings').mockReturnValue(fooObj)

  const result = myFunction()

  expect(result).toBe(fooObj.foo)
})


If foo is primitive (like in your test), you need to update the object property if the value

function myFunction() {
  const settings = getSettings()
  // operation on setting.foo (if foo is primitive)
  return setting.foo
}

And pass the object in the test and not the primitive value

it('', async () => {
  const obj = {foo: '123'}

  jest.spyOn(getSettings, 'foo').mockReturnValue(obj)

  const result = myFunction()

  expect(result).toBe(obj.foo)
})

When you passed foo in your tests you passed it by value, you need to pass it by reference

about 4 years ago · Juan Pablo Isaza Report
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!