简体   繁体   English

如何在反应中测试连接组件内的功能?

[英]How do I test function inside connected component in react?

I have a component which is connected to store. 我有一个连接到商店的组件。 And I have to test a function inside the react component. 我必须在react组件中测试一个函数。 How can I reach to that function? 我怎样才能达到这个功能?

Eg: 例如:

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);
`

You can mock connect function to return you the required object(s) so that you can access them in the test environment. 您可以模拟connect函数以返回所需的对象,以便您可以在测试环境中访问它们。

This way, you will be able to access newReactComponent and then you can mount the react component(using shallow from enzyme). 这样,您将能够访问newReactComponent,然后您可以安装反应组件(使用浅的酶)。

After mounting you will be able to access the class methods. 安装后,您将能够访问类方法。

Something like this: 像这样的东西:

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

I have answered a similar question here 在这里回答了类似的问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在连接的React-Redux组件内部测试componentWillMount? - How to test componentWillMount inside a connected React-Redux component? 如何通过将Redux连接的React组件导出为PureComponent来测试它? - How do you test a redux connected react component by exporting it as a PureComponent? 如何在反应组件内测试 function? - How to test a function inside react component? 反应测试。 如何测试反应组件内的功能 - React Test. how to test function inside react component 如何在反应中从地图函数内部更改组件? - How do I change the component from inside a map function in react? 在Typescript React项目中,如何实例化连接的组件? - In a Typescript React project how do I instantiate a connected component? 如何测试一个反应连接的组件以及测试什么组件? - How to test a react connected component and what to test of component? 如何测试在其父级上调用函数的 React 组件,这会更改组件上的 props? - How do I test a React component that calls a function on its parent, which changes props on the component? 如何在Enzyme / React中测试包含连接到Redux的组件的组件? - How to test component that contains a component connected to Redux in Enzyme / React? 在React / Redux中测试连接的组件 - Test connected component in React/Redux
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM