简体   繁体   English

如何对该将Redux连接到React组件的实用程序进行单元测试?

[英]How would I unit test this utility that connects Redux to React components?

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: 我有一个名为“ reduxify”的“实用程序”,它会自动为您执行很多Redux / React样板,因此您不必像在每个组件上编写“ mapStateToProps”和“ mapDispatchToProps”功能,而是像这样编写组件:

// 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 Reduxify函数(带有注释)位于以下要点: 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? 所以,这是一个问题:模拟组件(可以访问提供者的组件)的最佳方法是什么,以便我可以对该吸盘进行单元测试,将其放到那里以供人们使用和使用,而不是像黑客一样?

Have a look at the unit tests used by react-redux for an example of how to test a component that is wrapped by <Provider> : https://github.com/reactjs/react-redux/blob/master/test/components/Provider.spec.js#L50-64 . 看一下react-redux使用的单元测试,以获取有关如何测试<Provider>包装的组件的示例: https : //github.com/reactjs/react-redux/blob/master/test/components /Provider.spec.js#L50-64 Basically, they just declared a component and then wrapped it with a <Provider> component whose store prop is a mocked Redux store. 基本上,他们只是声明了一个组件,然后用<Provider>组件将其包装,该组件的store道具是模拟的Redux商店。 (They're using 'react-addons-test-utils' to do their test component rendering, but it would be even easier with enzyme.) (他们正在使用“ react-addons-test-utils”进行测试组件渲染,但是使用酶将更加容易。)

In your case, you could spy on the mocked store's dispatch() method to ensure that your component's action-dispatching props are calling it as expected. 在您的情况下,您可以监视模拟商店的dispatch()方法,以确保组件的动作调度道具正在按预期方式对其进行调用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM