Error: It looks like you called `mount()` without

2020-03-12 06:02发布

问题:

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
*/