【发布时间】:2022-01-23 03:58:25
【问题描述】:
我有以下函数使用fetch() 进行 API 调用:
export async function fetchCars(dealershipId) {
return request('path/to/endpoint/' + dealershipId)
.then((response) => {
if (response.ok === false) {
return Promise.reject();
}
return response.json();
})
.then((cars) => {
return parseMyCars(cars);
});
}
我想测试调用何时失败(特别是返回return Promise.reject() 时)。我现在有以下 Jest 测试:
(fetch as jest.Mock).mockImplementation(() =>
Promise.resolve({ ok: false })
);
const result = await fetchCars(1);
expect(request).toHaveBeenCalledWith('/path/to/endpoint/1');
expect(result).toEqual(Promise.reject());
但我在运行测试时收到Failed: undefined 消息。我试过使用:
(fetch as jest.Mock).mockRejectedValue(() =>
Promise.resolve({ ok: false })
);
但收到类似的Failed: [Function anonymous] 消息。
在这里测试被拒绝的承诺的正确方法是什么?
【问题讨论】:
-
const result = await fetchCars(1);抛出一个错误,因为 promise 被拒绝,所以测试失败,函数调用结束并且没有达到断言。expect(result).toEqual(Promise.reject());无论如何都没有意义 - 等待被拒绝的承诺的结果不是被拒绝的承诺,而是抛出错误。另请注意,测试错误总是很棘手,因为您可能会意外地编写非错误路径为误报的代码。根据jestjs.io/docs/asynchronous,您可能想使用.rejects。
标签: javascript jestjs ts-jest jest-fetch-mock