0

I have a "utility" called "reduxify" that automatically does a lot of the Redux/React boilerplate for you, so that instead of writing "mapStateToProps" and "mapDispatchToProps" functions on every component, you just write your component like this:

// usage. 

class Foo extends Component {
  // component stuff
}

export default reduxify(actions, Foo); 

The reduxify function (with comments) are at this gist: https://gist.github.com/brianboyko/904d87da2a75c98e8cd5f5352dd69d57

Without the comments (for brevity), it's produced below:

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);
}

So, here's the question: What's the best way to mock a component (one that will have access to the Provider) so that I can unit test this sucker, put it out there for people to use and enjoy, and not feel like a hack?

4

1 回答 1

3

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

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

于 2016-05-11T08:50:20.470 回答