如何为调用 reduxjs 的 mapStateToProps 的 React 组件编写单元测试?

How can I write a unit test for a react component that calls reduxjs's mapStateToProps?

我正在尝试为名为 AsyncApp 的容器组件编写单元测试,但出现以下错误“mapStateToProps 必须 return 一个对象。而是收到未定义的。”。 =24=]

这是我的设置。

Root.js

import configureStore from '../configureStore';
import React, { Component } from 'react';
import { Provider } from 'react-redux';
import AsyncApp from './AsyncApp';

const store = configureStore();

export default class Root extends Component {
  render() {
    return (
      <Provider store={store}>
        <AsyncApp />
      </Provider>
    );
  }
}

configureStore.js

import { createStore, applyMiddleware } from 'redux';
import thunkMiddleware from 'redux-thunk';
import createLogger from 'redux-logger';
import rootReducer from './reducers';

const loggerMiddleware = createLogger();

const createStoreWithMiddleware = applyMiddleware(
  thunkMiddleware
  //loggerMiddleware
)(createStore);

export default function configureStore(initialState) {
  return createStoreWithMiddleware(rootReducer, initialState);
}

AsyncApp.js

import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';
import { foo } from '../actions';
import FooComponent from '../components/FooComponent';

class AsyncApp extends Component {
  constructor(props) {
    super(props);
    this.onFoo= this.onFoo.bind(this);
    this.state = {}; // <--- adding this doesn't fix the issue
  }

  onFoo(count) {
    this.props.dispatch(foo(count));
  }

  render () {
    const {total} = this.props;

    return (
      <div>
        <FooComponent onFoo={this.onFoo} total={total}/>
      </div>
    );
  }
}

function mapStateToProps(state) {
  return state;
}

export default connect(mapStateToProps)(AsyncApp);

我在测试中将 store 直接传递给 AsyncApp 以避免出现以下运行时错误:Could not find "store" in either the context or props of "Connect(AsyncApp)". Either wrap the root component in a <Provider>, or explicitly pass "store" as a prop to "Connect(AsyncApp)".

测试尚未完成,因为我无法通过 mapStateToProps 错误消息。

AsyncApp-test.js

jest.dontMock('../../containers/AsyncApp');
jest.dontMock('redux');
jest.dontMock('react-redux');
jest.dontMock('redux-thunk');
jest.dontMock('../../configureStore');

import React from 'react';
import ReactDOM from 'react-dom';
import TestUtils from 'react-addons-test-utils';
const configureStore = require( '../../configureStore');
const AsyncApp = require('../../containers/AsyncApp');

const store = configureStore();

//const asyncApp = TestUtils.renderIntoDocument(
  //<AsyncApp store={store} />
//);

const shallowRenderer = TestUtils.createRenderer();
shallowRenderer.render(<AsyncApp store={store}/>);

我想最终测试 AsyncApp 包含一个 FooComponent,并且在调用 onFoo 时调度一个 foo 动作。

我想做的事情可以实现吗?我这样做正确吗?

我在一些地方看到的建议是测试 non-connected 组件,而不是连接版本。因此,请验证当您将特定道具传递给您的组件时,您是否获得了预期的渲染输出,并验证当您传递具有特定形状的状态时,您的 mapStateToProps() returns 是预期的部分。然后你可以期望它们放在一起时应该都能正常工作。