React+Enzyme+Redux Error: Method “simulate” is meant to be run on 1 node. 0 found instead

React+Enzyme+Redux Error: Method “simulate” is meant to be run on 1 node. 0 found instead

我是 Jest 和 Enzyme 的新手,我正在尝试找出解决此错误的方法。我已经尝试了所有可能的解决方案(还有 Whosebug 上的解决方案)。

如果这不是正确的方法,我将不胜感激。

我想测试什么?

一个组件(名为 Company),它有一个按钮 'Add',单击它会打开一个模式(由状态控制)。 因此,我想测试是否在单击按钮时,用于控制模态可见性的状态从 'false' 更改为 'true'。

我目前的方法:

查看文档和关于 Whosebug 的大量答案,我根据对我有用的方法修改了我的代码

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()但还是不行。

您忘记了 css 选择器:)

const button = wrapper.find('#companyAdd');