问题
I am testing a react component using Enzyme and I'm getting the following error:
Invariant Violation: dangerouslyRenderMarkup(...): Cannot render markup in a worker thread. Make sure
window
anddocument
are available globally before requiring React when unit testing or use ReactDOMServer.renderToString for server rendering
I added the following setup for jsdom, before requiring 'enzyme' (as I read in few places):
const baseMarkup = '<!DOCTYPE html><html><head><title></title></head><body></body></html>';
const window = require('jsdom').jsdom(baseMarkup).defaultView;
global.window = window;
global.document = window.document;
global.navigator = window.navigator;
const React = require('react');
const {mount} = require('enzyme');
const sinon = require('sinon');
const SortableInput = require('../../../src/components/sortableInput/sortableInput').default;
What am I doing wrong here?
EDIT
I don't think it is related to server side rendering. The message is general about unit testing and server side rendering.
回答1:
Answering my own question, in case someone have the same issue. This was what eventually worked for me:
import 'jsdom-global/register';
describe('My awesome component test', () => {
let cleanup;
beforeEach(() => cleanup = require('jsdom-global')());
afterEach(() => cleanup());
....
})
回答2:
In one of my project, this is the code to initialise JSDOM, and it is working fine.
import { jsdom } from 'jsdom';
before(() => {
global.document = jsdom('');
global.window = document.defaultView;
});
The before() is a root hook for Mocha. It runs before the beginning of all tests.
回答3:
One more not so obvious reason for the same error is the describeWithDOM
method from Enzyme:
describeWithDOM('<Slider />', () => {
describe('render', () => {
it('should render the slider with one handle by default', () => {
// and so on
According to enzyme guide now it is better to avoid this method:
In previous versions of enzyme, there was a public describeWithDOM API which loaded in a new JSDOM document into the global namespace before every test, ensuring that tests were deterministic and did not have side-effects.
This approach is no longer recommended. React's source code makes several assumptions about the environment it is running in, and one of them is that the global.document that is found at "require time" is going to be the one and only document it ever needs to worry about. As a result, this type of "reloading" ends up causing more pain than it prevents.
It is important, however, to make sure that your tests using the global DOM APIs do not have leaky side-effects which could change the results of other tests. Until there is a better option, this is left to you to ensure.
来源:https://stackoverflow.com/questions/39436899/react-enzyme-error-invariant-violation-dangerouslyrendermarkup-cannot