我正在尝试使用jest为我的Web组件项目编写测试。我已经使用了带有es2015预设的babel。当加载js文件时,我遇到了一个问题。我遵循了一个代码片段,其中document
对象具有currentScript
对象。但在测试上下文中,它是null
。因此,我想模拟相同的情况。但是jest.fn()
并没有真正帮助解决这个问题。我该如何处理这个问题?
jest失败的代码片段。
var currentScriptElement = document._currentScript || document.currentScript;
var importDoc = currentScriptElement.ownerDocument;
我已经编写了一个测试用例。component.test.js
import * as Component from './sample-component.js';
describe('component test', function() {
it('check instance', function() {
console.log(Component);
expect(Component).toBeDefined();
});
});
以下是 Jest 抛出的错误信息:
Test suite failed to run
TypeError: Cannot read property 'ownerDocument' of null
at src/components/sample-component/sample-component.js:4:39
更新: 根据Andreas Kö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';
describe('component test', function() {
it('check instance', function() {
console.log(Component);
expect(Component).toBeDefined();
});
});
但是没有运气
更新:我已经尝试了上面的代码,没有使用__dev__
。同时将文档设置为全局变量。
global.document
吗? - Pavithra Kodmad