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

152
Visualizações
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 à 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