我试图用笑话为我的web组件项目编写测试。我已经在es2015预设中使用了babel。加载js文件时遇到问题。我有以下一段代码,其中document
对象有currentScript
对象。但在测试环境下,它是null
。所以我想嘲笑它一样。但jest.fn()
是不是真的有帮助。我该如何处理这个问题?在笑话中嘲笑`文档'
一段代码,其中笑话失败。
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();
});
});
以下是笑话
Test suite failed to run
TypeError: Cannot read property 'ownerDocument' of null
at src/components/sample-component/sample-component.js:4:39
更新抛出的错误: 按照由安德烈亚斯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'? –
yes..i have try that .. no luck .. – thecodejack
因此,我基本上使用jsdom,如 'const jsdom = require('jsdom'); const documentHTML ='<!doctype html>
'; global.document = jsdom.jsdom(documentHTML); ' 在此之后,我会根据我想要的任何文档以及我的测试中可用的文档。 –