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

后端 未结 3 1575
借酒劲吻你
借酒劲吻你 2021-01-11 16:44

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

3条回答
  •  迷失自我
    2021-01-11 17:10

    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

提交回复
热议问题