2015-04-07 41 views
1

我想为反应路由器路由模块写一个简单的笑话测试。反应路由器的最佳测试

该组件有一个按钮,当点击它时,通过使用'transitionTo'方法有一个程序导航到另一个路线。

我不断收到以下错误,即使添加了stubRouterContext utils的后(如解释here),并在stubRouterContext包裹我的UserDetails组件:

TypeError: Property 'transitionTo' of object #<Object> is not a function

我使用的反应12.2,反应路由器12.4,和2.2笑话

我的虚设部件:

var Navigation, React, Router; 

React = require('react/addons'); 
Router = require('react-router'); 
Navigation = require('react-router').Navigation; 

module.exports = React.createClass({ 

    mixins: [Navigation], 

    onButtonClick: function() { 
    this.transitionTo('next-page'); 
    }, 

    render: function() { 
    return (<button onClick={@onButtonClick}>Go to next page</button>) 
    } 
}); 

我的测试文件:

jest.dontMock('./../utils/stub-router-context') 
    .dontMock('../dummy-component'); 

describe('DummyComponent', function() { 
    it('let you navigate to next page', function() { 

    var React = require('react/addons'); 
    var TestUtils = React.addons.TestUtils; 
    var stubRouterContext = require('./../utils/stub-router-context'); 
    var DummyComponent = require('../dummy-component'); 

    var Subject = stubRouterContext(DummyComponent); 
    dummyComponent = TestUtils.renderIntoDocument(<Subject/>); 

    button = TestUtils.findRenderedDOMComponentWithTag(dummyComponent, 'button'); 
    React.addons.TestUtils.Simulate.click(button); 

    }); 
}); 

我的存根路由器context.cjsx文件:

var React = require('react/addons'); 
var func = React.PropTypes.func; 
var _ = require('lodash'); 

module.exports = function(Component, props, stubs) { 
    return React.createClass({ 
    childContextTypes: { 
     makePath: func, 
     makeHref: func, 
     transitionTo: func, 
     replaceWith: func, 
     goBack: func, 
     getCurrentPath: func, 
     getCurrentRoutes: func, 
     getCurrentPathname: func, 
     getCurrentParams: func, 
     getCurrentQuery: func, 
     isActive: func 
    }, 
    getChildContext: function() { 
     return _.merge({}, { 
     makePath: function() {}, 
     makeHref: function() {}, 
     transitionTo: function() {}, 
     replaceWith: function() {}, 
     goBack: function() {}, 
     getCurrentPath: function() {}, 
     getCurrentRoutes: function() {}, 
     getCurrentPathname: function() {}, 
     getCurrentParams: function() {}, 
     getCurrentQuery: function() {}, 
     isActive: function() {} 
     }, stubs); 
    }, 
    render: function() { 
     return React.createElement(Component, props); 
    } 
    }); 
}; 
+0

看一看在回购的testing.md文件https://github.com/rackt/react-router/blob/master/docs/guides/testing.md – CharlesJHardy

回答

1

您需要访问反应的上下文功能。添加contextTypes你的课......

module.exports = React.createClass({ 
    contextTypes: { 
    router: React.PropTypes.func 
    }, 

    ... 

然后使用context.router像transitionTo拨打:

this.context.router.transitionTo('Ads', {adID: 100}); 

更多信息可以在这里找到:

https://github.com/rackt/react-router/blob/master/docs/api/RouterContext.md

Jfyi:我目前使用的是React 13.1和React-router 13.2