【发布时间】:2017-05-16 08:55:46
【问题描述】:
我有一个智能组件,正在尝试编写单元测试(DOM 测试) - 收到以下错误:不知道为什么我会收到此错误,即使我在测试中传递了道具..?
Invariant Violation:在“Connect(myComponent)”的上下文或道具中找不到“store”。要么将根组件包装在 a ,或显式将“store”作为道具传递给 “连接(我的组件)”。
更新了新错误:TypeError: Cannot read property 'mainData' of undefined at mapStateToProps
测试代码:
import React from 'react';
import ReactDOM from 'react-dom';
import TestUtils from 'react-addons-test-utils';
import { Provider } from 'react-redux';
import configureMockStore from 'redux-mock-store';
import { renderComponent, expect } from '../../test_helper';
import myComponent from '../../../src/containers/myComponent';
describe('myComponent', () => {
const mockStore = configureMockStore();
let connectedApp,
store,
initialItems;
let component;
let componentRender;
beforeEach(() => {
const DataMock = [1, 2, 0, 0, 0, 0, 0, 1, 2, 0, 0, 0, 0,
0, 1, 2, 0, 0, 0, 0, 0, 1, 2, 0, 0, 0, 0, 0, 1,
2, 0, 0, 0, 0, 0];
const props = {
mainData: DataMock,
abc: 'def',
subData: {
test: '1',
testing: 12,
},
userID: '1',
Date: 'jan11',
};
initialItems = ['one'];
const initialState = {
items: initialItems
};
store = mockStore(initialState);
component = TestUtils.renderIntoDocument(
<Provider store={store}><myComponent {...props} /></Provider>);
componentRender = ReactDOM.findDOMNode(component);
});
it('loads', () => {
expect(component).to.exist;
});
});
这个 myComponent 是一个哑组件的子组件
我的组件代码:
import React, { PropTypes, Component } from 'react';
import { connect } from 'react-redux';
import * as actions from '../../actions/component_actions';
class myComponent extends Component {
constructor(props) {
super(props);
this.state = {
someString: 'abc',
someotherstring: 'def',
};
}
componentDidMount() {
const { test1, test2, test3 } = this.props;
this.props.fetchEntriesDefault(test1, test2, test3);
this.props.fetchAnalyticsMainView(test1, test2, test3);
}
render() {
return (
<div className="container">
</div>
);
}
}
function mapStateToProps(state) {
return {
mainData: state.reducerName.mainData,
subDataData: state.reducerName.subDataData,
};
}
myComponent.propTypes = {
mainData: PropTypes.array,
abc: PropTypes.string,
subDataData: PropTypes.object,
userID: PropTypes.string,
actioncreatorfuncone: PropTypes.func,
actioncreatorfunctwo: PropTypes.func,
date: PropTypes.string,
};
export default connect(mapStateToProps, actions)(myComponent);
【问题讨论】:
标签: reactjs redux mocha.js react-redux enzyme