如何测试Promise的回调中收到的响应?

时间:2019-07-17 12:04:43

标签: unit-testing jestjs enzyme

我有一个类似下面的测试用例

it('should get response as expected', () => {
    const expected = {test: 'test};
    serviceRequest().then((response) => {
        expect(response).toEqual(expected);
    })
});

不管期望匹配中的内容是什么,它总是会通过。

1 个答案:

答案 0 :(得分:1)

您至少有两个选择...如果您退还诺言,Jest将等到该诺言解决

it('should get response as expected', () => {
    const expected = {test: 'test};
    return serviceRequest().then((response) => {
        expect(response).toEqual(expected);
    })
});

或者(根据我的喜好),您可以进行测试async。如果这样做,则可以等待您的答复并在下一行进行检查:

it('should get response as expected', async () => {
    const expected = {test: 'test};
    await response = serviceRequest();
    expect(response).toEqual(expected);
});

Jest文档涵盖了这些和其他注意事项-see here