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

后端 未结 3 1576
借酒劲吻你
借酒劲吻你 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

    0 讨论(0)
  • 2021-01-11 17:14

    just put the following in top of your test file

    /**
     * @jest-environment jsdom
    */
    
    0 讨论(0)
  • 2021-01-11 17:17
    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.

    0 讨论(0)
提交回复
热议问题