Jest测试中的`requestAnimationFrame` polyfill错误

Yan*_*Tay 22 reactjs jestjs react-dom

在我运行Jest单元测试时升级到React后出现此错误:

React取决于requestAnimationFrame.确保在旧版浏览器中加载polyfill.

我如何解决它?

我正在使用Jest 18.1.0.

Atu*_*tul 33

找到了解决方法!

脚步:

  1. 创建文件 __mocks__/react.js
  2. 将以下内容添加到 __mocks__/react.js

const react = require('react');
// Resolution for requestAnimationFrame not supported in jest error :
// https://github.com/facebook/react/issues/9102#issuecomment-283873039
global.window = global;
window.addEventListener = () => {};
window.requestAnimationFrame = () => {
  throw new Error('requestAnimationFrame is not supported in Node');
};

module.exports = react;
Run Code Online (Sandbox Code Playgroud)

  1. 跑开!

正如对代码的评论所标记的那样

这是来自https://github.com/facebook/react/issues/9102#issuecomment-283873039的解决方案

  • 我使用 redux-observable 和 RxJs,我需要添加:`window.cancelAnimationFrame = window.clearTimeout` 和 `window.requestAnimationFrame = (cb) => window.setTimeout(cb, 1000 / 60)`(我从代码中获得灵感在 RxJS 中) (2认同)

Sos*_*ska 33

这对我有用:

  1. 安装 raf

npm install --saveDev raf 要么 yarn add -D raf

  1. setupFiles在您的jest配置中添加polyfill ,package.json如下所示:

'setupFiles': ['raf/polyfill']

注意:如果此阵列中有其他安装文件,则可能需要先放置raf/polyfill.

  • @kirsteng它是[jest config](https://facebook.github.io/jest/docs/en/configuration.html#setupfiles-array)属性之一.顺便说一句,这个解决方案对我有用,欢呼! (2认同)

sba*_*ler 9

如果您只是需要将其填充进行测试,那么您实际上并不需要限制.

使用以下代码创建一个新文件:

global.requestAnimationFrame = function (cb) {
    return setTimeout(cb, 0);
};
Run Code Online (Sandbox Code Playgroud)

将该文件添加到jest/setupFilespackage.json中的数组中.

  • 我已将此添加到我的安装文件中,但仍然收到警告. (3认同)

smf*_*ote 7

如果您使用 create-react-app,其中一些解决方案将无法正常工作(或者根本无法正常工作,在 的情况下setupFiles)。什么工作得很好是src/setupTests.js在那里创建一个文件并在那里添加你的模拟:

global.requestAnimationFrame = (cb) => { cb(); };
Run Code Online (Sandbox Code Playgroud)

您还可以在其中添加其他全局模拟(例如localStoragenavigator.serviceWorker)。