我正在尝试为被调用的容器组件编写单元测试,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 (); } }
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 (); } } 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
测试尚未完成,因为我无法通过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( ////); const shallowRenderer = TestUtils.createRenderer(); shallowRenderer.render( );
我想最终测试AsyncApp
包含a FooComponent
,并foo
在onFoo
调用时调度一个动作.
我想要做到的是可以实现的吗?我是以正确的方式来做这件事的吗?
我在几个地方看到的建议是测试非连接组件,而不是连接版本.因此,验证当您将特定道具传递给组件时,您将获得预期的渲染输出,并验证当您传入具有特定形状的状态时,您mapStateToProps()
将返回预期的碎片.那么你可以期待它们在放在一起时都能正常工作.