Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Jest test for async promise with async/await

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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')
    })
})
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading