我正在尝试以开玩笑的方式为我的Web组件项目编写测试.我已经使用了带有es2015预设的babel.我在加载js文件时遇到问题.我已经跟踪了一段代码,其中document对象有一个currentScript对象.但在测试环境中它是null.所以我在想同样的嘲笑.但是jest.fn()并没有真正的帮助.我该如何处理这个问题?
一段代码,其中开玩笑失败.
var currentScriptElement = document._currentScript || document.currentScript;
var importDoc = currentScriptElement.ownerDocument;
Run Code Online (Sandbox Code Playgroud)
我写的测试用例. component.test.js
import * as Component from './sample-component.js';
describe('component test', function() {
it('check instance', function() {
console.log(Component);
expect(Component).toBeDefined();
});
});
Run Code Online (Sandbox Code Playgroud)
以下是jest抛出的错误
Test suite failed to run
TypeError: Cannot read property 'ownerDocument' of null
at src/components/sample-component/sample-component.js:4:39
Run Code Online (Sandbox Code Playgroud)
更新: 根据AndreasKöberle的建议,我添加了一些全球变量,并试图嘲笑如下
__DEV__.document.currentScript = document._currentScript = {
ownerDocument: ''
};
__DEV__.window = {
document: __DEV__.document
}
__DEV__.document.registerElement = jest.fn();
import * as Component from './arc-sample-component.js'; …Run Code Online (Sandbox Code Playgroud)