2016-12-14 27 views
4

如何編寫單元測試以確保mapDispatchToProps正確返回包裝在調度功能中的動作創建者?我應該如何在Redux中測試mapDispatchToProps?

我目前使用摩卡和酵素進行測試。

這是我的容器組件。

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) 

回答

5

我真的建議你嘗試這樣做。除非你有一個非常特殊的需求,以不尋常的方式使用dispatch,否則我鼓勵你只使用connect支持的對象簡寫語法。如果您將一個充滿動作創建者的對象作爲connect的第二個參數傳遞給它,它將自動通過bindActionCreators爲您運行該對象。所以,在這種情況下,它將是export default connect(mapState, LayerActions)(App)

我確實看到您將該調用的結果作爲名爲actions的道具返回。我開始自己做這件事,但最終轉而離開它,因爲它需要我的一些組件「知道」他們已連接到Redux(即,必須致電this.props.actions.someActionCreator()而不是this.props.someActionCreator())。

我寫了一篇名爲Idiomatic Redux: Why use action creators?的文章,詳細介紹了其中的一些主題。

+0

很好。非常感謝。如果我將對象字面量作爲第二個參數傳入,那麼如何將由Connect注入的注入操作傳遞到邊欄子組件? – therewillbecode

+0

您通常需要將動作相關的道具放在一起,然後傳遞給他們。這可能是顯式的('const {firstAction} = props'),或者更像是一個全面的('const {layers,... allOtherProps} = props')。無論哪種方式,提取它們,然後使用這些道具渲染側邊欄。 – markerikson

相關問題