首页 > 解决方案 > 在 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我的测试吗?

标签: javascriptjestjs

解决方案


我认为您走在正确的轨道上...将您的global.requestAnimationFrame线路更改为:

        Object.defineProperty(window, "requestAnimationFrame", {
          writable: true,
          value: callback => callback()
        });

推荐阅读