我在react组件中有此方法以在componentDidMount时加载Google Recaptcha API。
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');
};
我在Jest测试文件中模拟
document
时遇到问题,因为d
仅具有Document { location: [Getter/Setter] }
,因此,其他对象是undefined
。我尝试在Jest配置中将
setupFiles
添加为other people said in another question:"setupFiles": ["<rootDir>/__mocks__/documentMock.js"]
documentMock.js:
Object.defineProperty(document, 'currentScript', {
value: document.createElement('script'),
});
但是没有运气。有人修好了吗?
还尝试了这个:
beforeAll(() => {
global.document: { //code }
})
Pd:这是错误:
TypeError: Cannot read property 'parentNode' of undefined
谢谢。
最佳答案
与jsdom一起使用setupFiles:
__mocks __ / client.js
import { JSDOM } from "jsdom"
const dom = new JSDOM()
global.document = dom.window.document
global.window = dom.window
然后在您的笑话配置中:
"setupFiles": [
"./__mocks__/client.js"
],
关于javascript - 在Jest测试文件中模拟文档,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46644563/