Home How should I unit test mapDispatchToProps in Redux?
Reply: 1

How should I unit test mapDispatchToProps in Redux?

therewillbecode
1#
therewillbecode Published in 2016-12-14 17:25:32Z

How should write a unit test to ensure that mapDispatchToProps correctly returns action creators that are wrapped in the dispatch function?

I am currently using Mocha and Enzyme for testing.

Here is my container component.

import { Component } from 'react'
import { connect } from 'react-redux'
import Sidebar from '/components/Sidebar'
import Map from '/components/Map'
import * as LayerActions from '../actions/index'

// Use named export for unconnected component (for tests)
export const App = ({layers, actions} ) => (
    <div>
     <Sidebar LayerActions={actions} />
     <Map /> 
    </div>
)

export const mapStateToProps = state => ({
  layers: state.layers
})

export const mapDispatchToProps = dispatch => ({
    actions: bindActionCreators(LayerActions, dispatch)
})

// Use default export for the connected component (for app)
export default connect(mapStateToProps, mapDispatchToProps)(App)
markerikson
2#
markerikson Reply to 2016-12-14 17:36:15Z

I would actually suggest that you not try to do that. Unless you have a very specific need to make use of dispatch in an unusual way, I'd encourage you to just use the object shorthand syntax that connect supports. If you pass an object full of action creators as the second argument to connect, it will automatically run that object through bindActionCreators for you. So, in this case it would be export default connect(mapState, LayerActions)(App).

I do see that you're returning the results of that call as a prop named actions. I started off doing that myself, but eventually switched away from it, as it required some of my components to "know" that they were connected to Redux (ie, having to call this.props.actions.someActionCreator() instead of this.props.someActionCreator()).

I wrote an article called Idiomatic Redux: Why use action creators? that covers some of these topics in more detail.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.324785 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO