Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

219
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!