【发布时间】:2018-03-20 13:14:39
【问题描述】:
我在一个 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 而不是尝试手动模拟 dom :)
标签: javascript reactjs recaptcha jestjs