Search code examples
reactjsjestjsreact-dom

`requestAnimationFrame` polyfill error in Jest tests


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.


Solution

  • Found a workaround!

    Steps:

    1. Create the file __mocks__/react.js (see about __mocks__ folder here)
    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