【问题标题】:How do I test function inside connected component in react?如何在反应中测试连接组件内的功能?
【发布时间】:2016-04-13 02:40:52
【问题描述】:

我有一个连接到商店的组件。而且我必须在反应组件中测试一个函数。我如何才能使用该功能?

例如:

var newReactComponent = React.createClass({
    functionToBeTested: function(){
        this.props.actions.fetchAll();
    }
});
var mapStateToProps = function (state) {
        return {
            cars: state.carReducer.cars
        }
    };

    var mapDispatchToProps = function (dispatch) {
        return {
            actions: bindActionCreators(_.assign({}, carActions, apiActions), dispatch)
        }
    };

    module.exports = connect(mapStateToProps, mapDispatchToProps)(newReactComponent);
`

【问题讨论】:

    标签: reactjs redux jestjs


    【解决方案1】:

    您可以模拟连接函数以返回所需的对象,以便您可以在测试环境中访问它们。

    这样,您将能够访问 newReactComponent 然后您可以挂载反应组件(使用来自酶的浅层)。

    挂载后,您将能够访问类方法。

    类似这样的:

    const actions = {fetchAll: jest.fn()}
    const wrapper = shallow(<newReactComponent actions={actions} />);
    wrapper.instance().functionToBeTested();
    expect(actions.fetchAll).toBeCalled();

    我已经回答了类似的问题here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-11
      • 1970-01-01
      • 2020-07-17
      • 2020-11-28
      • 2018-08-24
      相关资源
      最近更新 更多