React Rendering Mocha, DOMException Invalid Document
Using React 13.2 and looking at lifecycle testing with a setup like the one shown in this gist . If I don't stop subsequent renders (using the shouldComponentUpdate method ), then something is causing the rendering (after the initial one) with a DOMException Wrong Document :
DOMException: Wrong document
at core.Node.insertBefore (D:\development\projects\fsm\node_modules\jsdom\lib\jsdom\level1\core.js:583:13)
at core.Node.insertBefore (D:\development\projects\fsm\node_modules\jsdom\lib\jsdom\level2\events.js:326:32)
at insertChildAt (D:\development\projects\fsm\node_modules\react\lib\DOMChildrenOperations.js:34:14)
at Object.DOMChildrenOperations.processUpdates (D:\development\projects\fsm\node_modules\react\lib\DOMChildrenOpertions.js:106:11)
The JSDOM frees up the password as the parent node is not a document and does not have the same owner document as the inserted child. Yes. How can the owner document be anything other than global if React doesn't do something funky under the hood.
Just surprised I don't see more people having a similar problem? There is nothing strange about setting up Mocha or JSX components. Plus the initial rendering is going well.
source to share
Update for node 4
With node 4 we can use the latest jsdom and solve this problem better, eg. using testdom .
This is how I test a React 0.13 component with mocha on node 4:
import testDom from "testdom";
import { expect } from "chai";
testDom("<html><body></body></html>");
const React = require("react/addons");
const MyTestableComponent = require("../src/MyTestableComponent");
const ExecutionEnvironment = require("react/lib/ExecutionEnvironment");
ExecutionEnvironment.canUseDOM = true;
describe("MyTestableComponent", () => {
it("works!", () => {
const component = <MyTestableComponent />;
expect(true).to.equal(true);
})
})
Note that we should require
, not import
React and the component.
Previous answer
I could fix this issue by following the OP's own comment on the question.
Since React stores document
in an internal variable when needed, we need to remove React from the object require.cache
before requesting it again:
var jsdom = require("jsdom").jsdom;
var React, TestUtils;
describe("Example", function() {
beforeEach(function() {
// remove react from the require cache
for (var key in require.cache) {
if (key.match(/\/node_modules\/react\//)) {
delete require.cache[key];
}
}
// init the DOM
global.document = jsdom("<html><head><script></script></head><body></body></html>");
global.window = document.parentWindow;
// require react again
React = require("react/addons");
TestUtils = React.addons.TestUtils;
});
// my tests...
});
source to share