我正在尝试为名为AsyncApp的容器组件编写单元测试,但出现以下错误“mapStateToProps必须返回一个对象。相反,它收到未定义的信息。”

这是我的设置。

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,并在调用foo时分派(dispatch)onFoo Action 。

我想做的是可以实现的吗?我要这样做正确吗?

最佳答案

我在几个地方看到的建议是测试未连接的组件,而不是已连接的版本。因此,请验证在将特定 Prop 传递到组件时是否获得了预期的渲染输出,并验证在以某种形状传递状态时mapStateToProps()返回了预期的片断。然后,您可以期望它们放在一起时都可以正常工作。

10-07 17:28