我的网络应用程序中包含以下代码:
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
时,此代码未涵盖,因为Jest不会执行requestAnimationFrame
,尽管它不会引发任何错误。我尝试通过将以下代码放入测试文件中来模拟requestAnimationFrame
,如here所述:
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
?
答案 0 :(得分:0)
我认为您走对了路...将您的 global.requestAnimationFrame
行更改为:
Object.defineProperty(window, "requestAnimationFrame", {
writable: true,
value: callback => callback()
});