使用 async/await 开玩笑地测试异步承诺

Jest test for async promise with async/await

我有这个函数,returns 承诺并在调用时失败:

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

我有这个测试,通过了:

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

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

但我觉得很奇怪,我希望它在函数调用之前调用 await:

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

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

最后一个没有通过,我不明白为什么。是不是语法不正确?

为了测试您希望承诺在期望的上下文中被拒绝的工作。 出于这个原因,我们通常这样写:

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

在您的特定示例中:

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

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

如果您想使用 Try/Catch 方法,只需捕获错误并确保错误是预期的错误:

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

        try{
            await mockAsync()
        }
        catch(err){
            expect(err.message).toEqual('Error')
        }
    })
})