我有一個名爲「HomeContainer」的容器,向我們展示了菜單和用戶列表。測試與酶反應容器
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import User from '../users/User';
import { getUsers } from '../users/UserActions';
import Menu from './components/Menu';
class HomeContainer extends Component {
constructor(props) {
super(props);
this.state = {
loading: true,
};
}
async componentDidMount() {
this.initialFetch();
}
async initialFetch() {
this.props.actions.getUsers();
this.setState({
loading: false,
});
}
render() {
return (
<section name="Home">
<Menu selected="Home" />
<section>
{this.state.loading && (
<h2>Loading users...</h2>
)}
{this.props.users.map(user => <User key={user.id} {...user} />)}
</section>
</section>
);
}
}
HomeContainer.propTypes = {
actions: PropTypes.arrayOf.isRequired,
users: PropTypes.arrayOf.isRequired,
};
function mapStateToProps(state) {
return {
users: state.users,
};
}
function mapDispatchToProps(dispatch) {
const actions = {
getUsers: bindActionCreators(getUsers, dispatch),
};
return { actions };
}
export default connect(mapStateToProps, mapDispatchToProps)(HomeContainer);
我試圖讓這個容器的測試獲取裏面的元素。但是我得到了很多錯誤。
import React from 'react';
import thunk from 'redux-thunk';
import {Provider} from 'react-redux';
import configureMockStore from 'redux-mock-store';
import { mount } from 'enzyme';
import HomeContainer from '../../source/pages/HomeContainer';
const middlewares = [thunk];
const mockStore = configureMockStore(middlewares);
describe("Testing the structure", function() {
let Component;
beforeEach(() => {
const user = { id: 1, email: 'aa', name: 'as' };
const store = mockStore({
users: [user],
});
const wrapper = mount(
<Provider store={store}>
<HomeContainer />
</Provider>
);
Component = wrapper.find(HomeContainer);
});
it("menu", function() {
const menu = Component.find('Menu');
expect(menu.length).toEqual(1);
});
it("section", function() {
const section = Component.find('section');
expect(section.length).toEqual(1);
});
});
測試的錯誤是:
TypeError: Cannot read property 'find' of undefined
at Object.<anonymous> (tests/pages/HomeContainer.test.jsx:30:27)
at node_modules/p-map/index.js:42:16
at process._tickCallback (node.js:369:9)
TypeError: Cannot read property 'history' of undefined
at Link.render (node_modules/react-router-dom/Link.js:76:35)
at node_modules/react-dom/lib/ReactCompositeComponent.js:796:21
任何想法?
但是,我必須導出組件連接。 導出默認連接(mapStateToProps,mapDispatchToProps)(HomeContainer); –
這是除了您的默認導出。這可以保持原樣。 – CLL