Error: It looks like you called `mount()` without a global document being loaded

旧街凉风 提交于 2019-12-04 00:39:52

问题


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


回答1:


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.

From Enzyme docs :

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 is a JavaScript based headless browser that can be used to create a realistic testing environment.

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'
};

Read Enzyme documentation - JSDOM for more informations




回答2:


npm install --save-dev --save-exact jsdom jsdom-global

Then:

import 'jsdom-global/register'; //at the top of file, even before importing React

More info here.

Alternative: In case you are using jest with enzyme-

In your package.json, specify the test environment for jest as jsdom as follows:

"jest": {
  "testEnvironment": "jsdom"
}

I faced the same issue and it worked well for me.




回答3:


just put the following in top of your test file

/**
 * @jest-environment jsdom
*/


来源:https://stackoverflow.com/questions/37104033/error-it-looks-like-you-called-mount-without-a-global-document-being-loaded

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!