`requestAnimationFrame` polyfill error in Jest tests

If you just need to polyfill it for tests, then you don't actually need the throttling.

Create a new file with this code:

global.requestAnimationFrame = function (cb) {
    return setTimeout(cb, 0);
};

Add that file to the jest/setupFiles array in your package.json.


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.


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