I have the following code in my web app:
const scroll = () => {
const scrollPerTick = (amountToScroll / 200) * 12;
if (scrolled < amountToScroll) {
container.scrollBy(0, scrollPerTick);
}
window.requestAnimationFrame(() => scroll(scrollBy));
};
if (scrolled < amountToScroll) {
window.requestAnimationFrame(scroll);
}
When I run Jest
, this code is not covered because requestAnimationFrame
is not executed by Jest, though it doesn't throw any error. I tried mocking requestAnimationFrame
by putting following code in my test file, as described 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);
But it didn't work. Is there any way to mock requestanimationFrame
in my tests?
I think you were on the right track... change your global.requestAnimationFrame
line to:
Object.defineProperty(window, "requestAnimationFrame", {
writable: true,
value: callback => callback()
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.