Nested components testing with Enzyme inside of React & Redux

后端 未结 6 1083
甜味超标
甜味超标 2020-12-24 05:55

I have a component SampleComponent that mounts another \"connected component\" (i.e. container). When I try to test SampleComponent by

6条回答
  •  生来不讨喜
    2020-12-24 06:55

    Option 1)

    You can wrap the container component with React-Redux's Provider component within your test. So with this approach, you actually reference the store, pass it to the Provider, and compose your component under test inside. The advantage of this approach is you can actually create a custom store for the test. This approach is useful if you want to test the Redux-related portions of your component.

    Option 2)

    Maybe you don't care about testing the Redux-related pieces. If you're merely interested in testing the component's rendering and local state-related behaviors, you can simply add a named export for the unconnected plain version of your component. And just to clarify when you add the "export" keyword to your class basically you are saying that now the class could be imported in 2 ways either with curly braces {} or not. example:

    export class MyComponent extends React.Component{ render(){ ... }}
    
    ...
    
    export default connect(mapStateToProps, mapDispatchToProps)(MyComponent)
    

    later on your test file:

    import MyComponent from 'your-path/MyComponent'; // it needs a store because you use "default export" with connect
    import {MyComponent} from 'your-path/MyComponent'; // don't need store because you use "export" on top of your class.
    

    I hope helps anyone out there.

提交回复
热议问题