我在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
感谢。
答案 0 :(得分:1)
将setupFiles与jsdom一起使用:
<强> __嘲笑__ / client.js 强>
import { JSDOM } from "jsdom"
const dom = new JSDOM()
global.document = dom.window.document
global.window = dom.window
然后在你的jest配置中:
"setupFiles": [
"./__mocks__/client.js"
],
答案 1 :(得分:1)
有no need to manually mock JSDOM in Jest。如果您在testEnvironment
文件中选择默认的jest.config.js
文件,它将被自动模拟:
testEnvironment: "jest-environment-jsdom",
如果您想使用JSDOM中未实现的某些DOM功能,只需在official docs之后对它们进行模拟,例如
window.matchMedia = jest.fn().mockImplementation(query => {
return {
matches: false,
media: query,
onchange: null,
addListener: jest.fn(),
removeListener: jest.fn(),
};
});