【发布时间】:2021-03-09 01:31:50
【问题描述】:
我是 Jest 和 Enzyme 的新手,我正在尝试找出解决此错误的方法。我已经尝试了所有可能的解决方案(还有那些在 stackoverflow 上的)。
如果这不是正确的方法,我将不胜感激。
我想测试什么?
一个组件(名为 Company),它有一个“添加”按钮,单击它会打开一个模式(由状态控制)。 因此,我想测试在按钮单击时,用于控制模态可见性的状态是否从“false”变为“true”。
到目前为止我的方法:
浏览文档和stackoverflow上的很多答案,我已经根据对我有用的方法修改了我的代码
Company.js
import React from 'react';
import { Modal Col, Label, Row, Card, CardBody, CardColumns, CardHeader } from 'reactstrap';
import { connect } from 'react-redux';
import MUIDataTable from "mui-datatables";
const columns = [/*table data headers */ ]
export class Company extends React.Component {
state = {
show: false,
}
}
handleShow = () => {...}
componentDidMount() {
this.fetchCompanies();
}
fetchCompanies = () => { /*API calls */ }
render() {
const options = {
filterType: 'checkbox',
selectableRows:false,
customToolbar:() => {
return <Button className="btn btn-primary" id="companyAdd" onClick={this.handleShow}>Add</Button>
}
}
return (
<div>
<Col xs="12" lg="12">
<MUIDataTable
columns={columns}
options={options}
/>
</Col>
<Col xs="12" lg="12">
<Modal isOpen={this.state.showChangePwd}></Modal>
</div>
);
}
}
const mapDispatchToProps = dispatch => ({..});
function mapStateToProps(state) {..}
export default connect(mapStateToProps,mapDispatchToProps)(Company);
我正在尝试在选项对象(内部渲染)中找到按钮
Company.test.js
import ReactDOM from "react-dom";
import {Company} from "../Company";
import { cleanup} from "@testing-library/react";
import "@testing-library/jest-dom";
import { configure, mount, shallow , render} from "enzyme";
afterEach(cleanup)
it("renders without crashing", () => {
expect(render(<Example/>))
})
it("renders button correctly", () => {
const onButtonClickMock = jest.fn();
const wrapper = shallow(<Example updateSelectedDashboard={onButtonClickMock}/>)
expect(wrapper.state('show')).toEqual(false);
const button = wrapper.find('companyAdd');
button.simulate('click')
expect(wrapper.state('show')).toEqual(true);
})
我也尝试过.dive(),即使没有成功。
【问题讨论】:
标签: unit-testing react-redux jestjs enzyme react-testing-library