Reputation: 223
I'm new to TDD and unit testing my js, and am looking into using the mocha/react shallow renderer to test my React components. My test component looks something like this:
var React = require('react');
var test = React.createClass({
render: function() {
return (
<div>My custom test component ({this.props.testAttribute})</div>
);
},
testFunction: function () {
return true;
}
});
module.exports = test;
So in addition to shallow rendering and making sure the component is rendering the way i need it to (which i can do now), i also want to test testFunction(), and make sure that is behaving as well. How would I go about doing that?
Upvotes: 1
Views: 297
Reputation: 1707
I think this depends on what kind of function your testFunction is.
If it is closely related to the rendering, e.g. it is an onClickHandler, then I would test this in combination with the rendering. Shallow rendering might not be sufficient here, you may need a real DOM (check out jsDOM and/or the enzyme testing library).
If the function does some calculations that are not tightly coupled to the rendering, then you might consider extracting it to its own file (think of aspects like modularity and separation of concerns here). This way, you can test it individually just like any other JavaScript code.
If you actually want to test the function individually while it is inside the component, you need a real DOM. A mocha/must test would look like this:
import jsdom from "jsdom";
import TestUtils from "react/lib/ReactTestUtils";
describe("Component Test", function () {
beforeEach(function () {
global.document = jsdom.jsdom("<!doctype html><html><body></body></html>");
global.window = global.document.defaultView;
this.component = TestUtils.renderIntoDocument(<MyComponent/>);
});
afterEach(function () {
delete global.document;
delete global.window;
});
it("test the function", function () {
expect(this.component.testFunction()).to.be(true);
});
});
Upvotes: 2