【问题标题】:How would I unit test this utility that connects Redux to React components?我将如何对这个将 Redux 连接到 React 组件的实用程序进行单元测试?
【发布时间】:2016-05-11 03:44:07
【问题描述】:

我有一个名为“reduxify”的“实用程序”,它会自动为您执行大量 Redux/React 样板文件,因此您无需在每个组件上编写“mapStateToProps”和“mapDispatchToProps”函数,您只需将组件编写为这个:

// usage. 

class Foo extends Component {
  // component stuff
}

export default reduxify(actions, Foo); 

reduxify 函数(带有 cmets)的要点如下: https://gist.github.com/brianboyko/904d87da2a75c98e8cd5f5352dd69d57

没有 cmets(为简洁起见),它在下面产生:

import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import { getStore } from '../store/storeConfig'

export function reduxify(actions, component){ 
  let mapStateToProps = (state) => {
    state = Object.assign({}, state, {store: state}, {getStore: getStore});
    return (state);
  }
  let prepareActions = (actions) => (dispatch) =>
    ({ actions: bindActionCreators(actions.default, dispatch),
       dispatch: dispatch,
     })
  let mapDispatchToProps = (dispatch) => (prepareActions(actions, dispatch))
  return connect(mapStateToProps, mapDispatchToProps)(component);
}

所以,问题来了:模拟组件(可以访问提供程序的组件)的最佳方法是什么,以便我可以对这个傻瓜进行单元测试,把它放在那里供人们使用和享受,而不是感觉像黑客一样?

【问题讨论】:

    标签: javascript unit-testing redux react-redux enzyme


    【解决方案1】:

    查看 react-redux 使用的单元测试示例,了解如何测试由 <Provider>:https://github.com/reactjs/react-redux/blob/master/test/components/Provider.spec.js#L50-64 包装的组件。基本上,他们只是声明了一个组件,然后用一个 <Provider> 组件包装它,该组件的 store 属性是一个模拟的 Redux 存储。 (他们正在使用 'react-addons-test-utils' 进行测试组件渲染,但使用酶会更容易。)

    在您的情况下,您可以监视模拟商店的 dispatch() 方法,以确保您的组件的动作调度道具按预期调用它。

    【讨论】:

      猜你喜欢
      • 2016-05-09
      • 2018-03-12
      • 1970-01-01
      • 2019-06-02
      • 1970-01-01
      • 2017-07-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多