使用React Test库编写测试用例是个新手。
这是我的组件
import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
class MyContainer extends React.Component {
static propTypes = {
graphicalData: PropTypes.object.isRequired,
};
render() {
const { graphicalData } = this.props;
return (
graphicalData && (
<div>
/////some action and rendering
</div>
))}
}
const mapStateToProps = (state) => {
return {
graphicalData: state.design.contents ? state.design.contents.graphicalData : {},
};
};
const mapDispatchToProps = (dispatch) => ({});
export default connect(mapStateToProps, mapDispatchToProps)(MyContainer)));
所以我正在使用React测试库编写我的测试用例文件
import React from 'react';
import '@testing-library/jest-dom';
import { render, cleanup, shallow } from '@testing-library/react';
import MyContainer from '../../MyContainer';
import configureMockStore from 'redux-mock-store';
import ReactDOM from 'react-dom';
const mockStore = configureMockStore();
import { Provider } from 'react-redux';
const store = mockStore({
state: {
design: {
contents: {
graphicalModel: { cars: [{},{}], bikes: [{},{}] },
},
},
},
});
afterEach(cleanup);
it('renders without crashing', () => {
const div = document.createElement('div');
ReactDOM.render(
<Provider store={store}>
<MyContainer />
</Provider>,
div
);
ReactDOM.unmountComponentAtNode(div);
});
我不确定出了什么问题,我的想法是检查组件是否加载而没有崩溃,如果cars数组长度大于0,请检查页面上呈现的内容。
但是我遇到了一些错误,任何关于例子或建议的帮助都会挽救我的一天
错误似乎是正确的。检查已传递到mockStore()
函数中的结构。它是
state: {
design: {
contents: {
graphicalModel: { cars: [{},{}], bikes: [{},{}] },
},
},
},
因此,当你在MyContainer中访问时,你应该将其作为访问
state.state.design.contents
只是在状态对象中有一个额外的层次结构。
或者,如果您不想更改组件,请将传递到mockStore()
方法中的状态结构更改为:
const store = mockStore({
design: {
contents: {
graphicalModel: { cars: [{},{}], bikes: [{},{}] },
},
},
});