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

223
Visualizações
How can I handle a promise in Jest?

I'm getting an error right in this part of my code. Received promise resolved instead of rejected and I'm not sure how to handle this, can anyone help me?

it("should not create a media if the user doesn't exist", async () => {
    user.user= undefined;
    await usersRepository.save(user);

    await expect(
      createMedia.execute({
        userId: user.id,
        type: 'video',
        media: 'video-media',
        description: 'description',
      }),
    ).rejects.toBeInstanceOf(AppError);
  });

And:

expect(received).rejects.toThrow()

    Received promise resolved instead of rejected
    Resolved to value: {"description": "description", "id": "id number", "media": "video-media", "userId": "id user", "type": "video"}
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Your code is creating a successful promise, which you then test against a rejects, so it fails because it executes successfully and you're telling it that you expect it to fail.

When you use .rejects you're telling the expect that you expect it to fail and be rejected, in this case it's succeeding. If you change that to a resolves instead of a rejects, it will work.

Or you have to make sure that the query you're doing will actually fail by i.e. updating something that doesn't exist.

Another way is to actually execute your query, get the result from it and then do an expect assertation on the return data.

For more clarity a normal promise looks like this:

const example = () => new Promise((resolve, reject) => ...

Then you can call those resolve and reject methods depending on whether the promise resolved correctly or if it failed you can call the reject. When you use .resolves or .rejects in jest it's testing those resolve and reject methods on the promise.

When you're using an async function you don't actually see that, but it's doing the same thing.

What's more is when users upload more files than they actually can, it will break, which is why in your case it actually doesn't fail, because then it actually does get rejected.

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