Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

189
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda