javascript - 在 Jest 中模拟 requestAnimationFrame
问题描述
我的网络应用程序中有以下代码:
const scroll = () => {
const scrollPerTick = (amountToScroll / 200) * 12;
if (scrolled < amountToScroll) {
container.scrollBy(0, scrollPerTick);
}
window.requestAnimationFrame(() => scroll(scrollBy));
};
if (scrolled < amountToScroll) {
window.requestAnimationFrame(scroll);
}
当我运行时Jest
,这段代码没有被覆盖,因为requestAnimationFrame
它没有被 Jest 执行,尽管它不会抛出任何错误。我尝试requestAnimationFrame
通过将以下代码放入我的测试文件中进行模拟,如此处所述:
const { JSDOM } = require('jsdom');
const jsdom = new JSDOM('<!doctype html><html><body></body></html>');
const { window } = jsdom;
function copyProps(src, target) {
Object.defineProperties(target, {
...Object.getOwnPropertyDescriptors(src),
...Object.getOwnPropertyDescriptors(target),
});
}
global.window = window;
global.document = window.document;
global.navigator = {
userAgent: 'node.js',
};
global.requestAnimationFrame = function (callback) {
return setTimeout(callback, 0);
};
global.cancelAnimationFrame = function (id) {
clearTimeout(id);
};
copyProps(window, global);
但它没有用。有什么方法可以模拟requestanimationFrame
我的测试吗?
解决方案
我认为您走在正确的轨道上...将您的global.requestAnimationFrame
线路更改为:
Object.defineProperty(window, "requestAnimationFrame", {
writable: true,
value: callback => callback()
});
推荐阅读
- python - for循环和多个CSV文件的问题
- php - 使用 php web hook 修改 HTML 元素
- python - 如何在 ANTLR 中定义起始规则?
- javascript - SVG 到图像导出性能问题(使用 canvg / XMLSerializer / getComputedStyle)
- php - 发布列
- android - 联系人更新到数据库不与 ContentObserver 一起使用
- angular - ngrx - 从商店中为多个可观察对象选择多个项目
- python - 重构更长的“单行”if-condition-assignment(三元 If)的 Pythonic 方式
- node.js - 通过事件网格传递来自 Azure Function 的 HTTP 请求
- c++ - 带参数的累积正态分布函数的逆