user_mda user_mda - 1 year ago 145
Node.js Question

Jest for ReactJS test

I have the following test for my React component

var React = require('react/addons');
var Router = require('react-router').Router;
var Route = require('react-router').Route;
var Link = require('react-router').Link;
TestUtils = React.addons.TestUtils;

describe('Navigation', function() {
var Navigation = require('../js/components/Navigation');

var NavElement = TestUtils.renderIntoDocument(
<Navigation items={[{ title: 'test' }, { title: 'test' }]} />

var items = TestUtils.scryRenderedDOMComponentsWithTag(NavElement, 'li');

it('renders each item as a li', function() {



Here is the React Component

'use strict'
var React = require('react');
var Router = require('react-router').Router;
var Link = require('react-router').Link;
var RouteHandler = require('react-router').RouteHandler;

var Navigation = React.createClass({
render: function() {
return (
<li><Link to="clusters">Clusters</Link></li>
<li><Link to="dependencies">Dependencies</Link></li>
<li><Link to="components">Components</Link></li>
<RouteHandler />
module.exports = Navigation;

BUt the test fails with the following error

- Expected 0 to equal 2.
at jasmine.buildExpectationResult (node_modules/jest-jasmine2/src/index.js:80:44)
at Object.eval (src/main/__tests__/app-test.js:23:26)
at Object.<anonymous> (node_modules/jest-jasmine2/src/jasmine-pit.js:35:32)
at jasmine2 (node_modules/jest-jasmine2/src/index.js:253:7)
at (node_modules/jest-cli/src/Test.js:44:12)
at process._tickCallback (node.js:369:9)
1 test failed, 0 tests passed (1 total in 1 test suite, run time 1.518s)

What am I missing?

Answer Source

You are calling jest.dontMock after you require the module. You must dot it before or your module will still be mocked: you will obtain a dummy component that does not implement any logic.

Also, while it is not the topic of your question, I do not think your component is doing what you want it to do. The provided items property is not used at all by your component. Currently, your component will always be rendered with the 3 <li> you defined in his rendered function. I would suggest you to have a quick look at the react tutorial and in particular how to use props.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download