我正在尝试开玩笑地为我的 Web 组件项目编写测试。我已经在 es2015 预设中使用了 babel。我在加载 js 文件时遇到问题。我遵循了一段代码,其中 document
对象有一个 currentScript
目的。但在测试上下文中它是 null
.所以我想 mock 同样的。但是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__
的情况下尝试了上面的代码.也可以通过将文档设置为全局。
最佳答案
与其他人所说的类似,但不要尝试自己模拟 DOM,只需使用 JSDOM:
模拟 /client.js
import { JSDOM } from "jsdom"
const dom = new JSDOM()
global.document = dom.window.document
global.window = dom.window
然后在你的笑话配置中: "setupFiles": [
"./__mocks__/client.js"
],
关于jestjs - 开 Jest `document`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41098009/