node.js - 为什么 JSDOM 与 Sinon 假定时器一起使用时会进入无限循环?
问题描述
使用最新的 JSDOM (11.6.0),当与 Sinon 的假计时器一起使用时,我得到一个无限循环。
const sinon = require('sinon');
sinon.useFakeTimers();
require('jsdom'); // This line creates an infinite loop
我怎样才能避免这个无限循环?
解决方案
这是由新的 Performance API 引起的。
该实现使用 Date.now() 来校准时钟。这是功能:
// This function assumes the clock is accurate.
function calculateClockOffset() {
const start = Date.now();
let cur = start;
while (cur === start) {
cur = Date.now();
}
...
}
(来源,请注意此代码不在 JSDOM 中,而是在其依赖项之一 w3c-hr-time 中)
当你运行时sinon.useFakeTimers();
,它会模拟Date.now()
总是返回相同的值,因此上面的代码创建了一个无限循环。
解决方法是不模拟Date
,只有 setTimeout/setInterval 函数:
// Sinon 2.x
sinon.useFakeTimers('setTimeout', 'clearTimeout', 'setInterval', 'clearInterval');
// Sinon 3.x or higher
sinon.useFakeTimers({toFake:['setTimeout', 'clearTimeout', 'setInterval', 'clearInterval']});
推荐阅读
- winapi - 当控件没有焦点时获取 LVS_SHOWSELALWAYS 的 ListView 选择颜色?
- javascript - 您如何通过 Googlescript API 离开 googlegroup
- matlab - 来自带有 while 循环的函数的表 [MATLAB]
- python - 如何通过 python pandas 从特定点反向计算天数?
- testing - 当主要 rinkeby 水龙头网页不起作用时,如何在 21 年 9 月 20 日获得宠物项目的测试以太?
- reactjs - React-select 在使用初始加载值实现全选/取消全选时面临多个错误
- arrays - 编写 MIPS (32) 汇编代码将 A[2] 的内容与 B[2] 交换
- python - 如何使用列表中的正则表达式从 web 元素中提取字符串(python)
- unity3d - 无法在场景视图或游戏视图中查看 TextMeshPro (TMP) 文本
- java - 如何使用 JAVA 在 Selenium 中集成 API 和 UI 框架?