Mocking document.createRange for jest

Create a script that sets up the polyfill you want -- let's call it "mockument.js" for this example. Within the jest configuration of your package.json set setupFiles to point to this script:

"jest": {
  "setupFiles": ["raf/polyfill", "./scripts/mockument"]
}

As shown above, you can also use module names (e.g. raf/polyfill).

One sweet thing about this is that you can create your own module for common initial setups for testing and use them across several component libraries that need the functionality.

"jest": {
  "setupFiles": ["@nteract/mockument"]
},

I added the polyfill in setupTests.js as described in this thread.

if (window.document) {
    window.document.createRange = () => ({
        setStart: () => {},
        setEnd: () => {},
        commonAncestorContainer: {
            nodeName: 'BODY',
            ownerDocument: document,
        },
    });
}

For it to work with TypeScript I had to add // @ts-ignore above commonAncestorContainer.