jestjs - 开 Jest `document`

标签 jestjs jsdom babel-jest

我正在尝试开玩笑地为我的 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/

相关文章:

javascript - 如何使用 Jest 测试导入/导出?

javascript - 是否可以为 Knockout 绑定(bind)创建 DOM?

javascript - Enzyme/Jest Prop 测试失败

javascript - React.render 在 jsdom 中创建空子组件

node.js - npm install <module> 持续错误? ( Node gyp 构建?)

reactjs - React Native - Jest : Broken since update to 0. 56. 如何修复它?

javascript - 如何将 Jest 添加到 Parcel.js 中构建的 React 应用程序

jestjs - 用 Jest 和 Enzyme 覆盖空操作函数

debugging - jsdom 和 Contextify 错误

reactjs - 如何使用 babel-jest 转译测试