开玩笑地嘲笑“文档" [英] Mocking `document` in jest

查看:25
本文介绍了开玩笑地嘲笑“文档"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试开玩笑地为我的 Web 组件项目编写测试.我已经在 es2015 预设中使用了 babel.我在加载 js 文件时遇到问题.我遵循了一段代码,其中 document 对象有一个 currentScript 对象.但在测试上下文中它是 null.所以我想嘲笑同样的.但是 jest.fn() 并没有真正的帮助.我该如何处理这个问题?

I'm trying to write tests for my web components projects in jest. I already use babel with es2015 preset. I'm facing an issue while loading the js file. I have followed a piece of code where document object has a currentScript object. But in test context it is null. So I was thinking of mocking same. But jest.fn() is not really help in same. How can I handle this issue?

jest 失败的一段代码.

Piece of code where jest is failing.

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抛出的错误

Following is the error thrown by 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 的建议,我添加了一些全局变量并尝试模拟如下

Update: As per suggestion from Andreas Köberle, I have added some global vars and tried to mock like following

__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__ 的情况下尝试了上面的代码.也可以通过将文档设置为全局.

Update: I have tried above code without __dev__. Also by setting document as global.

推荐答案

与其他人所说的类似,但与其尝试自己模拟 DOM,只需使用 JSDOM:

Similar to what others have said, but instead of trying to mock the DOM yourself, just use JSDOM:

// __mocks__/client.js

import { JSDOM } from "jsdom"
const dom = new JSDOM()
global.document = dom.window.document
global.window = dom.window

然后在你的笑话配置中:

Then in your jest config:

    "setupFiles": [
      "./__mocks__/client.js"
    ],

这篇关于开玩笑地嘲笑“文档"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆