How to fix `TypeError: document.createRange is not a function` error while testing material ui popper with react-testing-library?
Referring to this github issue, I found out that we can fix the error with following code put in test set up file.
(global as any).document.createRange = () => ({
setStart: () => {},
setEnd: () => {},
commonAncestorContainer: {
nodeName: 'BODY',
ownerDocument: document,
},
});
The issue is with the underlying implementation of PopperJS calling the document.createRange
function when there is no DOM API for it to call. The solution is to mock PopperJS.
// __mocks__/popper.js.js
import PopperJs from 'popper.js';
export default class Popper {
constructor() {
this.placements = PopperJs.placements;
return {
update: () => {},
destroy: () => {},
scheduleUpdate: () => {}
};
}
}
jest will pick any mocks in the /__mocks__
directory automatically, so simply adding this file should fix your issue