Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

190
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda