I have this method in a react component to load the Google Recaptcha API when componentDidMount.
loadCaptcha = () => {
((d, s, id) => {
const element = d.getElementsByTagName(s)[0];
const fjs = element;
let js = element;
if (d.getElementById(id)) {
return;
}
js = d.createElement(s);
js.id = id;
js.src = '//google.com/recaptcha/api.js';
fjs.parentNode.insertBefore(js, fjs);
})(document, 'script', 'google-recaptcha');
};
I'm having problems mocking document
in a Jest test file because d
has only Document { location: [Getter/Setter] }
and, for that, the other objects are undefined
.
I have tried adding setupFiles
in Jest config, as other people said in another question:
"setupFiles": ["<rootDir>/__mocks__/documentMock.js"]
documentMock.js:
Object.defineProperty(document, 'currentScript', {
value: document.createElement('script'),
});
But with no luck. Has someone fixed that?
Also tried this:
beforeAll(() => {
global.document: { //code }
})
Pd: This is the error:
TypeError: Cannot read property 'parentNode' of undefined
Thanks.