Jest for ReactJS测试

时间:2016-06-08 20:21:25

标签: node.js unit-testing reactjs jestjs

我对我的React组件进行了以下测试

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');
jest.dontMock('../js/components/Navigation.js');


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

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


  it('renders each item as a li', function() {
    expect(items.length).toEqual(2);


  });


});

这是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 (
            <div>
            <header>
            <ul>
            <li><Link to="clusters">Clusters</Link></li>
            <li><Link to="dependencies">Dependencies</Link></li>
            <li><Link to="components">Components</Link></li>
            </ul>
            </header>
            <RouteHandler />
            </div>
            );
        }
    });
    module.exports = Navigation;

测试失败并出现以下错误

- 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 Test.run (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)

我错过了什么?

1 个答案:

答案 0 :(得分:0)

在之后您需要模块时调用jest.dontMock 。你必须在之前将它标记为,否则你的模块仍然会被模拟:你将获得一个不实现任何逻辑的虚拟组件。

此外,虽然这不是你问题的主题,但我认为你的组件并没有按照你的意愿去做。您的组件根本不使用提供的items属性。目前,您的组件将始终使用您在渲染函数中定义的3 <li>进行渲染。我建议你快速查看一下反应教程,特别是how to use props