I'm getting the following error when using Enzyme's mount
function while testing a React app in Jest from the command line. It says that a DOM environment is not loaded, which I would think means I need to set up JSDOM. However, it appears that JSDOM ships with Jest and is preconfigured according to Facebook's docs for Jest. Here's my test:
import React from 'react'
import MyComponent from '../src/components/MyComponent'
import { configure } from 'enzyme'
import Adapter from 'enzyme-adapter-react-16'
import { mount, shallow } from 'enzyme'
import { Menu, Dropdown, Modal } from 'semantic-ui-react'
import renderer from 'react-test-renderer';
configure({ adapter: new Adapter() })
test('it works', () => {
const wrapper = mount(
<MyComponent />
)
expect(wrapper.contains('foobar')).toEqual(true)
});
And here's the error:
Enzyme's mount expects a DOM environment to be loaded, but found none
at assertDomAvailable (node_modules/enzyme-adapter-utils/build/Utils.js:107:11)
at ReactSixteenAdapter.createMountRenderer (node_modules/enzyme-adapter-react-16/build/ReactSixteenAdapter.js:203:52)
at ReactSixteenAdapter.createRenderer (node_modules/enzyme-adapter-react-16/build/ReactSixteenAdapter.js:384:25)
at new ReactWrapper (node_modules/enzyme/build/ReactWrapper.js:96:54)
at mount (node_modules/enzyme/build/mount.js:19:10)
at Object.<anonymous> (test/LinesheetModal.test.js:12:37)
at new Promise (<anonymous>)
It appears to be related to enzyme-adapter-react-16. Any idea what could be wrong?
It looks like the problem was that JSDOM and Enzyme were not set up correctly. Adding this file as a preloaded file to Jest fixed it:
import Adapter from 'enzyme-adapter-react-16'
import { configure } from 'enzyme'
import jsdom from 'jsdom'
function setUpDomEnvironment() {
const { JSDOM } = jsdom;
const dom = new JSDOM('<!doctype html><html><body></body></html>', {url: 'http://localhost/'});
const { window } = dom;
global.window = window;
global.document = window.document;
global.navigator = {
userAgent: 'node.js',
};
copyProps(window, global);
}
function copyProps(src, target) {
const props = Object.getOwnPropertyNames(src)
.filter(prop => typeof target[prop] === 'undefined')
.map(prop => Object.getOwnPropertyDescriptor(src, prop));
Object.defineProperties(target, props);
}
setUpDomEnvironment();
configure({ adapter: new Adapter() })
Jest comes configured with JSDom out of the box, you need to make sure to use testEnvironment: jsdom
in your configuration.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With