React testing error: It looks like you called `mount()` without a global document being loaded React testing error: It looks like you called `mount()` without a global document being loaded reactjs reactjs

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


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).

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.

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 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.


I would recommend you two things that will probably fix your issue, first of all, do the mount in each describe, the reason behind this is that you should make each test independent of each other, so unless you start to use Rewire in your beforeEach, it is better to start each test in a clean situation.

As another suggestion, maybe you have more tests, but in this case, since your are only testing that the component was mounted and exist you can use shallow instead of mount, and that will only mount the component in a shallow mode, which will be faster, but will not trigger every life-cycle event of react.

Your final code should look like the following

import React from 'react';import { shallow } from 'enzyme';import Header from './';import { expect } from 'chai';describe('header component', () => {  describe('initial state', () => {    it('renders the header', () => {      const renderedOutput = shallow(<Header />)      expect(renderedOutput).to.exist();    });    it('renders the header', () => {      const renderedOutput = shallow(<Header />)      expect(renderedOutput).to.be.present();    });  })});

Let me know if it makes sense to you and more important, if it works.

Aditionally you may need to include the jsdom as you mention, see this related post here: Error: It looks like you called `mount()` without a global document being loaded