如何在Jest中强制超时来测试超时错误?



我们在React项目中有一个函数来获取商店列表。如果获取时间超过10秒,我们将中止请求并显示错误。

const controller = new AbortController();
const getTimeout = setTimeout(() => controller.abort(), 10000);
const fetchStores = storeId => (
ourFetchStoresFunction(`http://my-api/${storeId}`, {
headers: { 'x-block': 'local-stores' },
signal: controller.signal
})
.then((results) => {
clearTimeout(getTimeout);
return results
})
.catch((err) => { throw err; })
);

下面是fetchStores函数的基本测试:

it('fetchStores should return a stores array', () => {
storesAPI.fetchStores(MOCK_STORES)
.then((stores) => {
expect(Array.isArray(stores)).toBe(true);
})
.catch();
});

如何在Jest中模拟此超时?

.then块中调用setTimeout方法不工作。此外,我宁愿不要在测试过程中等待10秒钟。我查了jest.useFakeTimers,但是没有找到。

我可以测试全局计时器,阅读这里:jestjs。io/docs/timer-mocks可以使用jest spyOn函数。例如:

let timeoutSpy; 
beforeEach(() => { 
timeoutSpy = jest.spyOn(global, 'setTimeout'); 
}); 
afterEach(() => { 
jest.restoreAllMocks(); 
})

然后在你的测试中,你可以期待(tymepoutSpy).toHaveBeenCalledTimes(1);像这样的东西应该可以工作,在我的情况下工作。

在您的情况下,您也可以使用jest来嘲弄控制器。可以是这样的:

让abortSpy;

在同一个beforeEach中,你可以设置它:

abortSpy = jest.spyOn(AbortController.prototype, 'abort');

我想ourFetchStoresFunction函数类似于fetch?

最后,你可以模拟取函数,所以它需要很多时间来加载,它可以这样做:

> global.fetch = jest.fn(() =>   Promise.resolve({ // set some time })
> );

最新更新