如何使用Jest测试React Router?

时间:2015-07-22 19:00:45

标签: unit-testing reactjs react-router jestjs

我无法成功地使用SDDFGDFGReact Router进行测试。我正在使用

  • 反应0.13.3
  • react-router 0.13.3
  • jest 0.3.0
  • 节点0.10.33

并尝试过这些方法:

有确凿的例子吗?

"super-secret guide"中提到的this question的所有链接(不使用Jest)现已破坏。当我能够查看该指南时,它没有提供比上面列出的第一个链接更多的信息。

2 个答案:

答案 0 :(得分:1)

不确定这是否是您正在寻找的内容,但我通过编写一个帮助函数来解决这个问题,我在编写依赖于路由器状态的组件的jest测试时使用该函数。

//router-test-helper
var Router = require('react-router'),
    Route = Router.Route,
    TestLocation = require('react-router/lib/locations/TestLocation');

module.exports = function(React){
    TestUtils = React.addons.TestUtils;
    return {
        getRouterComponent: function(targetComponent, mockProps) {
            var component,
                div = document.createElement('div'),
                routes = [
                    React.createFactory(Route)({
                        name: '/',
                        handler: targetComponent
                    })
                ];

            location = new TestLocation('/');
            Router.run(routes, location, function (Handler) {
                var mainComponent = React.render(React.createFactory(Handler)(mockProps), div);
                component = TestUtils.findRenderedComponentWithType(mainComponent, targetComponent);
            });
            return component;
        }
    };
};

我自己并没有写下所有这些内容,我认为大部分内容都是从你现在已经关闭的指南中删除的。如果我没记错的话......已经有一段时间了。

在你有了这个之后,你可以在你的测试中使用它,就像这样。

//test-example
jest.dontMock('../src/js/someComponent');
var React = require('react/addons');
var TestUtils = React.addons.TestUtils;
var routerHelper = require('../router-test-helper')(React);
var SomeComponent = require('../srcs/js/someComponent');

describe('Some Component', function(){
    it('should be testable', function(){
        var mockProps = {}; 
        var renderedComponent = routerHelper.getRouterComponent(SomeComponent, mockProps);
        // Test your component as usual from here.....
        ///////////////////////////////////////////////

        var inputs = TestUtils.scryRenderedDOMComponentsWithTag(renderedComponent, 'input');
        //blah blah blah
    });
});

这假设你在unmocked模块路径中有React和helper

如果你真的试图测试某些特定路线的东西,或者在路线之间转换......我不确定这是不是一个好方法。可能更好地使用更多集成测试-y,比如硒等等。另外......一旦反应路由器的1.0出来,这可能不会起作用。但是,测试事物和反应方式(tm)可能更容易,因为所有路由内容都将通过道具来处理。至少这是我从我读过的那一点点得到的印象。

答案 1 :(得分:1)

对于碰巧遇到这个问题的人。 这是我最终为我的上下文相关组件设置的设置(当然,为简单起见而删除):

// dontmock.config.js contains jest.dontMock('components/Breadcrumbs')
// to avoid issue with hoisting of import operators, which causes 
// jest.dontMock() to be ignored

import dontmock from 'dontmock.config.js';
import React from "react";
import { Router, createMemoryHistory } from "react-router";
import TestUtils from "react-addons-test-utils";

import Breadcrumbs from "components/Breadcrumbs";

// Create history object to operate with in non-browser environment
const history = createMemoryHistory("/products/product/12");

// Setup routes configuration.
// JSX would also work, but this way it's more convenient to specify custom 
// route properties (excludes, localized labels, etc..).
const routes = [{
  path: "/",
  component: React.createClass({
    render() { return <div>{this.props.children}</div>; }
  }),
  childRoutes: [{
    path: "products",
    component: React.createClass({
      render() { return <div>{this.props.children}</div>; }
    }),
    childRoutes: [{
      path: "product/:id",
      component: React.createClass({
        // Render your component with contextual route props or anything else you need
        // If you need to test different combinations of properties, then setup a separate route configuration.
        render() { return <Breadcrumbs routes={this.props.routes} />; }
      }),
      childRoutes: []
    }]
  }]
}];

describe("Breadcrumbs component test suite:", () => {
  beforeEach(function() {
    // Render the entire route configuration with Breadcrumbs available on a specified route
    this.component = TestUtils.renderIntoDocument(<Router routes={routes} history={history} />);
    this.componentNode = ReactDOM.findDOMNode(this.component);
    this.breadcrumbNode = ReactDOM.findDOMNode(this.component).querySelector(".breadcrumbs");
  });

  it("should be defined", function() {
    expect(this.breadcrumbNode).toBeDefined();
  });

  /**
   * Now test whatever you need to
   */
相关问题