ReactJS 测试 Jest

Jest for ReactJS test

我对我的 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 组件

'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)

我错过了什么?

您正在调用 jest.dontMock 您需要该模块。您必须在 之前 点它,否则您的模块仍将被模拟:您将获得一个不实现任何逻辑的虚拟组件。

此外,虽然这不是您问题的主题,但我认为您的组件并未按照您的意愿行事。您的组件根本不使用提供的 items 属性。目前,您的组件将始终使用您在他的渲染函数中定义的 3 <li> 进行渲染。我建议您快速浏览一下 React 教程,尤其是 how to use props.