`requestAnimationFrame` polyfill error in Jest tes

2020-07-02 04:26发布

Got this error after upgrading to React when I ran my Jest unit tests:

React depends on requestAnimationFrame. Make sure that you load a polyfill in older browsers.

How do I fix it?

I'm using Jest 18.1.0.

8条回答
闹够了就滚
2楼-- · 2020-07-02 05:10

Found a workaround!

Steps:

  1. Create the file __mocks__/react.js
  2. Add the following into __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;

  1. Run jest !

As marked on comments on the code

This is the solution from https://github.com/facebook/react/issues/9102#issuecomment-283873039

查看更多
家丑人穷心不美
3楼-- · 2020-07-02 05:13

this worked for me:

  1. Install raf

npm install --saveDev raf or yarn add -D raf

  1. Add the polyfill to your setupFiles in your jest config in package.json like this:

'setupFiles': ['raf/polyfill']

Note: if you have other setup files in this array, you may want to put raf/polyfill first.

查看更多
登录 后发表回答