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

151
Vistas
Jest Mock issues with async functions with .then

i have the follow code

async function searchCharacter(){
   
  const response = await fetch("https://rickandmortyapi.com/api/character/?name=")
  .then((response) => {
      if(response.status !== 200) throw `HTTP error: ${response.status}`;
      const data = response.json();
     return data
    })
  .then( (body) => {
      const [first] = body.results;
      console.log(first)
  })
  .catch( (error) => {
      console.log(`Error: ${error}`)
  })
}

With this Jest Test

describe('searchCharacter', () => {

  it('gets the character data', async () => {

    const responses = {
      status: "200",
      json() => {return {name: "ricky"}}
    }

    fetch.mockResolvedValueOnce(responses);

    const char = await searchCharacter();
    expect(char.name).toBe("ricky")

  });
  
  });

and here is where i have the issue the follow output from running yarn test

TypeError: Cannot read property 'name' of undefined

      32 |
      33 |     const char = await searchCharacter();
    > 34 |     expect(char.name).toBe("ricky")
         |                 ^
      35 |
      36 |   });
      37 |   /*

      at Object.<anonymous> (tests/searchCharacter.test.js:34:17)

when i remove the .then() and reduce the complexity of the async function works the jest test, but i need the code to stay like this, i suppose there are some error or conflict when i pass the first .then() but i do not know how to solve.

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