如何在ComponentDidMount中存根函数并需要首先渲染组件?

时间:2015-10-13 22:19:06

标签: javascript unit-testing reactjs

我试图对反应组件进行单元测试,如下所示:

Component.jsx:

return React.createClass({
    render: function(){
        return (
                <div id='model' ref = 'model' >
                    <div className = 'container'>
                        {container}
                    </div>
                </div>
            );
    }

    componentDidMount: function () {
        this.props.model.getNext().then(doSth());

        React.findDOMNode(this.refs.model).addEventListener('focus', this.scroll);
    },

    scroll: function() {
        // do scrolling.
    }
});

所以我想测试componentDidMount中的逻辑,这需要存根addEventListener()。 问题是: 为了存根它我需要渲染以通过refs属性找到domnode,但是在渲染之后将立即调用componentDidMount,因此存根不会对该情况起作用。

例如:在单元测试中:

var eventFunction = {};
mockEventListener: function(event, callback){
    eventFunction[event] = callback;
}

var renderer = React.addons.TestUtils.renderIntoDocument(component, props);
sinon.sandbox.create().stub(React.findDOMNode(renderer.refs.model), 'addEventListener', mockEventListener);
eventFunction.focus();

这会抱怨eventFunction没有任何属性,因为在执行componentDidMount之后调用了存根,所以它被束缚了。 有没有办法在渲染之前存根函数或任何其他方法来正确测试这个单元?

0 个答案:

没有答案