测试react-app带ant-design/charts的终极解决方案
2023-09-03 01:43:43
问题
当我使用react-scripts
和@ant-design/charts
时,在运行Jest测试时出现问题。我收到了以下错误信息:
Jest did not exit one second after the test run has completed.
This usually means that there are asynchronous operations that weren't stopped in your tests. Consider running Jest with `--detectOpenHandles` to troubleshoot this issue.
这是因为@ant-design/charts
使用了一个称为requestAnimationFrame
的异步函数,Jest没有正确地清理它。这会导致Jest在测试运行后继续运行,并最终导致超时错误。
解决方案
1. 添加--detectOpenHandles
标志
要解决此问题,您需要在运行Jest时添加--detectOpenHandles
标志。这将指示Jest在测试运行后检查是否有任何未关闭的句柄,并帮助您识别导致问题的异步操作。
要添加--detectOpenHandles
标志,您可以在命令行中使用以下命令:
npx jest --detectOpenHandles
或者,您可以在Jest配置中启用detectOpenHandles
选项:
// jest.config.js
module.exports = {
detectOpenHandles: true,
};
2. 停止异步操作
一旦您启用了detectOpenHandles
选项,您就可以开始识别导致问题的异步操作。通常,这些操作是在测试完成后没有正确清理的计时器或动画帧请求。
要停止异步操作,您需要在测试完成后手动清除它们。这可以通过使用clearTimeout()
和cancelAnimationFrame()
函数来完成。
例如,以下代码演示了如何清除计时器和动画帧请求:
// test.js
afterEach(() => {
clearTimeout(timerId);
cancelAnimationFrame(animationFrameId);
});
3. 使用模拟函数
在某些情况下,您可能无法手动清除异步操作。在这种情况下,您可以使用模拟函数来模拟它们的行为。
例如,以下代码演示了如何模拟requestAnimationFrame
函数:
// test.js
jest.mock('requestAnimationFrame', () => {
return (callback) => {
callback();
};
});
通过模拟requestAnimationFrame
函数,您可以在测试完成后立即运行回调函数,从而避免超时错误。
结论
通过使用--detectOpenHandles
标志、停止异步操作和使用模拟函数,您可以解决在使用react-scripts
和@ant-design/charts
时运行Jest测试时遇到的问题。
我希望本文对您有所帮助!如果您有任何其他问题,请随时提出。