0

I have this function that returns a promise and fails when is called:

export const mockAsync = () => {
  return new Promise((_, reject) => {
    setTimeout(() => reject(new Error('Error')), 50);
  });
};

And I have this test, which is passing:

describe('mockAsync', () => {
  test('it should throw if we ask for it', async () => {
    const result = mockAsync();

    await expect(result).rejects.toThrow('Error');
  });
});

But I find it weird, I would expect it to call await before the function call:

describe('mockAsync', () => {
  test('it should throw if we ask for it', async () => {
    const result = await mockAsync();

    expect(result).rejects.toThrow('Error');
  });
});

This last one is not passing, and I cant understand why. Is not the correct syntax?

1
  • If you await mockAsync(), the rejected promise throws as an error. That's nothing to do with Jest, it's how the syntax works. Commented Jan 13, 2022 at 21:04

1 Answer 1

1

For the test the work you want the promise to be rejected within the context of the expect. for that reason we usually write it like this:

await expect(/*sync function call*/).rejects.toThrow('someError')

And in your particular example:

describe('mockAsync', () => {
    test('it should throw if we ask for it', async () => {

        await expect(mockAsync()).rejects.toThrow('Error')
    })
})

If you want to use the Try/Catch approach simply catch the error and make sure the error is the expected one:

describe('mockAsync', () => {
    test('it should throw if we ask for it', async () => {

        try{
            await mockAsync()
        }
        catch(err){
            expect(err.message).toEqual('Error')
        }
    })
})
Sign up to request clarification or add additional context in comments.

8 Comments

Now I get it, as it throws we need to be withing the expect context, or within a throw/catch statement
correct. in the try/catch scenario you will not use the expect().rejects way, you will simply expect the error you caught in the catch to equal the error you are expecting
May you add a try/catch example? Just for reference
@EmilleC. read the docs: jestjs.io/docs/asynchronous
@jonrsharpe great advice, except it isn't.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.