开玩笑嘲笑`document` [英] Mocking `document` in jest
问题描述
我正试图为我的Web组件项目编写测试.我已经在es2015预设中使用babel.加载js文件时遇到问题.我遵循了一段代码,其中document
对象具有currentScript
对象.但是在测试环境中,它是null
.所以我想嘲笑一样.但是jest.fn()
并不能真正起到帮助作用.我该如何处理这个问题?
I'm trying to write tests for my web components projects in jest. I already use babel with es2015 preset. I'm facing an issue while loading the js file. I have followed a piece of code where document
object has a currentScript
object. But in test context it is null
. So I was thinking of mocking same. But jest.fn()
is not really help in same. How can I handle this issue?
开玩笑失败的代码段.
var currentScriptElement = document._currentScript || document.currentScript;
var importDoc = currentScriptElement.ownerDocument;
我编写的测试用例. component.test.js
Test case I have written. component.test.js
import * as Component from './sample-component.js';
describe('component test', function() {
it('check instance', function() {
console.log(Component);
expect(Component).toBeDefined();
});
});
以下是玩笑引发的错误
Test suite failed to run
TypeError: Cannot read property 'ownerDocument' of null
at src/components/sample-component/sample-component.js:4:39
更新: 根据AndreasKöberle的建议,我添加了一些全局变量,并尝试模拟如下操作
Update: As per suggestion from Andreas Köberle, I have added some global vars and tried to mock like following
__DEV__.document.currentScript = document._currentScript = {
ownerDocument: ''
};
__DEV__.window = {
document: __DEV__.document
}
__DEV__.document.registerElement = jest.fn();
import * as Component from './arc-sample-component.js';
describe('component test', function() {
it('check instance', function() {
console.log(Component);
expect(Component).toBeDefined();
});
});
但是没有运气
更新:我尝试了不使用__dev__
的上述代码.也可以将文档设置为全局.
Update: I have tried above code without __dev__
. Also by setting document as global.
推荐答案
我已经在玩笑中使用setUpFiles
属性解决了此问题.这将在jsdom之后和每个适合我的测试之前执行.
I have resolved this using setUpFiles
property in jest. This will execute after jsdom and before each test which is perfect for me.
在Jest配置中设置setupFiles,例如:
Set setupFiles, in Jest config, e.g.:
"setupFiles": ["<rootDir>/browserMock.js"]
// browserMock.js
Object.defineProperty(document, 'currentScript', {
value: document.createElement('script'),
});
理想的情况是加载webcomponents.js来填充jsdom.
Ideal situation would be loading webcomponents.js to polyfill the jsdom.
这篇关于开玩笑嘲笑`document`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!