我在react组件中使用这个方法来加载Google Recaptcha API时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');
};
在Jest测试文件中模拟document
有问题,因为d
只有Document { location: [Getter/Setter] }
,因此其他对象是undefined
。
我尝试在Jest中添加setupFiles
,作为其他人在另一个问题上说:
"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
谢谢。
发布于 2018-05-31 16:06:30
在jsdom中使用setupFiles:
__mocks__/client.js
import { JSDOM } from "jsdom"
const dom = new JSDOM()
global.document = dom.window.document
global.window = dom.window
然后在您的jest配置中:
"setupFiles": [
"./__mocks__/client.js"
],
发布于 2018-10-21 23:10:04
有无需在Jest中手动模拟JSDOM。如果在testEnvironment
文件中选择默认的jest.config.js
文件,将自动对其进行模拟,即:
testEnvironment: "jest-environment-jsdom",
如果您想使用一些未在JSDOM中实现的DOM特性,只需按照官方文件来模拟它们,例如。
window.matchMedia = jest.fn().mockImplementation(query => {
return {
matches: false,
media: query,
onchange: null,
addListener: jest.fn(),
removeListener: jest.fn(),
};
});
发布于 2022-07-18 08:10:09
我来到这里专门嘲弄currentScript
,却找不到确切的答案。
这是我的解决办法:
./setupTests.ts
// Mock current script to be able to spy on it
Object.defineProperty(document, 'currentScript', {
configurable: true,
get() {
return document.createElement('script');
},
});
testFile.spec.ts
describe('Test Suite', () => {
afterEach(() => jest.clearAllMocks());
it('should test byproduct of document.currentScript.src', () => {
jest.spyOn(document, 'currentScript', 'get').mockReturnValue({ src: '' } as any);
// ... run code
});
});
https://stackoverflow.com/questions/46644563
复制相似问题