错误:您好像调用了`mount()`却没有加载全局文档 [英] Error: It looks like you called `mount()` without a global document being loaded

查看:299
本文介绍了错误:您好像调用了`mount()`却没有加载全局文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试安装用于酶测试的组件,并得到此错误。

I'm trying to mount a component for testing with enzyme, and get this error.

推荐答案

Mocha不会在浏览器环境中运行测试,因此没有DOM。要解决此问题,只需使用jsdom npm模块创建DOM。

Mocha doesn't run your test in a browser environment,so there is no DOM. To fix this problem, simply you have to use jsdom npm module to create a DOM.

来自酶文档


由于酶的mount API需要DOM,如果您尚未在浏览器环境(例如,节点
环境)中使用JSDOM,则需要
来使用挂载。

Since enzyme's mount API requires a DOM, JSDOM is required in order to use mount if you are not already in a browser environment (ie, a Node environment).

JSDOM是一个基于JavaScript的无头浏览器,可用于
创建一个真实的测试环境。

JSDOM is a JavaScript based headless browser that can be used to create a realistic testing environment.

为了获得最佳的酶体验,建议您加载一个
文档进入全局范围,然后需要第一次使用
的时间。在
React的代码运行之前运行以下脚本非常重要。

For the best experience with enzyme, it is recommended that you load a document into the global scope before requiring React for the first time. It is very important that the below script gets run before React's code is run.

因此,像下面这样的独立脚本通常是一个不错的选择。方法:

As a result, a standalone script like the one below is generally a good approach:



/* setup.js */

var jsdom = require('jsdom').jsdom;

var exposedProperties = ['window', 'navigator', 'document'];

global.document = jsdom('');
global.window = document.defaultView;
Object.keys(document.defaultView).forEach((property) => {
  if (typeof global[property] === 'undefined') {
    exposedProperties.push(property);
    global[property] = document.defaultView[property];
  }
});

global.navigator = {
  userAgent: 'node.js'
};

阅读酶文档-JSDOM 了解更多信息

这篇关于错误:您好像调用了`mount()`却没有加载全局文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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