【发布时间】:2023-03-08 22:51:02
【问题描述】:
我正在开玩笑地尝试为我的 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();
});
});
以下是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? -
是的..我试过了..没有运气..
-
-
其实这里的问题是,jsdom 非常简单并且没有webcomponents API。无论如何,根据我的回答暂时解决了它。
标签: jestjs jsdom babel-jest