I am new to reactJS and try to learn how to test with it. I have encouter the following testing util method. However i am keep getting the same error message:ReferenceError: document is not defined
.
renderIntoDocument
ReactComponent renderIntoDocument(
ReactElement instance
)
Render a component into a detached DOM node in the document. This function requires a DOM.
Note: You will need to have window, window.document and window.document.createElement globally available before you import React. Otherwise React will think it can't access the DOM and methods like setState won't work.
I know it the reason failing its missing the DOM, but how can i insert the DOM or require it?
My test below:
import expect from 'expect.js';
import React from 'react';
import Header from '../../components/header';
import {renderShallow} from './help';
import ReactAddOn from 'react/addons';
var TestUtils = ReactAddOn.addons.TestUtils;
describe('Test react', function() {
let component;
beforeEach(()=>{
component = TestUtils.renderIntoDocument(<Header></Header>);
});
it('Test if the content been correclty render', function() {
console.log(component);
});
});
tl;dr; You need
jsdom
+Mocha
.According to spec
ReactTestUtils#renderIntoDocument
,renderIntoDocument() requires a DOM:
Traditionally, Unit testing in React is done using
Jest
, which apparently contains DOM support. AndMocha
doesn't.To understand this, consider this overly simplify analogy,
Jest
=Mocha
+jsdom
.jsdom
is implemented in JavaScript, we can have a DOM-like API to work with without needing a browser. That means that we don’t have to capture a browser in order test, likeKarma
(which is why it works the moment you useKarma
). Hence, we can run our tests in environments without browsers, like in Node or in continuous integration environments.References:
You need a DOM. Fortunately, jsdomify makes it easy to attach a DOM to your globals in Node.
Suppose we have a simple component:
We can test this with
renderIntoDocument
. Here's an example using tape: