Home > Software design >  How can I handle a promise in Jest?
How can I handle a promise in Jest?

Time:11-06

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({
        performerId: 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"}

CodePudding user response:

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.

  • Related