React测试库无waitFor时,如何移除测试文件中的setTimeout?
解决方案
针对你使用的@testing-library/react-hooks@5.0.3版本(无waitFor方法),可以用以下两种方案移除setTimeout:
方案一:使用waitForNextUpdate(推荐)
这个版本的renderHook会返回waitForNextUpdate方法,专门用于等待hook的下一次状态更新,完全适配hook测试场景,比定时器模拟更精准。
修改后的测试代码:
describe('filters onClick', () => { it.only('should update the colour filter and call the hook again with colour selection when the colour onClick function is called', async () => { const { result, waitForNextUpdate } = renderHook(useFilters); expect(getOption(result.current.filters.colours, 'Green').selected).toBeFalse(); act(() => { getOption(result.current.filters.colours, 'Green').onClick('Green'); }); // 等待hook完成异步更新 await waitForNextUpdate(); expect(getOption(result.current.filters.colours, 'Green').selected).toBeTrue(); }); });
方案二:使用Jest定时器模拟
如果hook内部的异步逻辑基于setTimeout实现,可以用Jest的假定时器来跳过等待:
describe('filters onClick', () => { it.only('should update the colour filter and call the hook again with colour selection when the colour onClick function is called', async () => { // 启用假定时器 jest.useFakeTimers(); const { result } = renderHook(useFilters); expect(getOption(result.current.filters.colours, 'Green').selected).toBeFalse(); act(() => { getOption(result.current.filters.colours, 'Green').onClick('Green'); }); // 执行所有待处理的定时器 jest.runAllTimers(); // 或者指定时间前进:jest.advanceTimersByTime(100); expect(getOption(result.current.filters.colours, 'Green').selected).toBeTrue(); // 清理假定时器 jest.useRealTimers(); }); });
为什么waitForElement没用?
waitForElement是@testing-library/react中用于查找DOM元素的方法,而你这里是测试自定义hook,没有DOM元素,所以完全不适用。
内容的提问来源于stack exchange,提问作者vicgoyso
相关产品推荐
相关产品推荐

