简体   繁体   中英

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:

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?

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')
    })
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM