Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should I unit test mapDispatchToProps in Redux?

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)
like image 552
therewillbecode Avatar asked Dec 14 '16 17:12

therewillbecode


People also ask

How do you write test cases for Maptatetoprops?

Steps: extract each mapDispatchToProps property as a separate action creator function in another file. extract each mapStateToProps property as a separate selector function in another file. write tests for the selectors and action creators.

What is mapStateToProps and mapDispatchToProps?

mapStateToProps is a function that you would use to provide the store data to your component, whereas mapDispatchToProps is something that you will use to provide the action creators as props to your component.


Video Answer


1 Answers

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.

like image 96
markerikson Avatar answered Nov 04 '22 06:11

markerikson