如何在React JS中使用Jest模拟组件的渲染方法

时间:2019-11-29 07:55:46

标签: reactjs unit-testing jestjs enzyme

我有一个名为“ ContactList”(反应组件)的列表,它的渲染方法内部,我称为另一个组件“ SimpleTable”,而在simpletable组件内部我称为“ ConfirmDialog”。现在,我尝试为ContactList编写测试用例,但是会生成错误:

import React from 'react'
import { shallow } from 'enzyme'
import ContactList from '../../components/ContactList/ContactList';
import { render } from '@testing-library/react';
import configureMockStore from "redux-mock-store";
import { configure} from "enzyme";
import { Provider } from "react-redux";
import Adapter from 'enzyme-adapter-react-16'
import ConfirmDialog from "../../components/UI/ConfirmationDialog/ConfirmationDialog"

configure({
  adapter: new Adapter()
})
jest.mock('react-router');

const mockStore = configureMockStore();
const store = mockStore({});

describe('Contact List', () => {

    const assetRecord = '{"assetID": "XXX","jurisdiction": "XXX","noofliens": "4,0,4","numberOfLienCountActive": 4,"numberOfLienCountRedeemed": 0,"ownerName": "XXX","parcelID": "SSS","propertyAddress": "CCC","stateName": "NNNN","totalDue": "222"}'

    beforeEach(() => {
      localStorage.setItem("assetRecord", assetRecord)
    })


    const fieldProps = {
        getContactListByAssetId: jest.fn(() => {
            return Promise.resolve([{}])
        }),

        deleteContactById:jest.fn(() => {
            return Promise.resolve([{}])
        }),

        confirmDialogCallback:jest.fn(() => {
            return Promise.resolve([{}])
        }),

        assetContactList:[
            {
                "cellPhone": "XXX",
                "company": "XXX",
                "contactAddress": "XXXX",
                "contactId": 291,
                "doNotContactFlag": false,
                "name": "XXXX",
                "typeName": "XXXX"
            }
        ]
    }
   it("should render without throwing an error", () => {
        expect(
            shallow(
                <Provider store={store}>
                    <ContactList />
                </Provider>
            )
        );
    });

    it('renders a without crashing', () => {
        render(
            <Provider store={store}>
                <ContactList {...fieldProps} />
            </Provider>)
    })
});

现在,它会产生以下错误:

     ● Contact List › renders a without crashing

    TypeError: Cannot read property 'showFlagConfirmation' of undefined

      45 | export const mapStateToProps = (state) => {
      46 |   return {
    > 47 |     showFlagConfirmation: state.events.showFlagConfirmation,
         |                                        ^
      48 |     isFlagApiProcessing: state.events.isFlagApiProcessing,
      49 |   }
      50 | }

我在确认对话框组件中使用了这两个属性。我该如何解决这些错误?如何为联系人列表页面编写测试用例?

联系人列表组件代码:

     <div className="fui-wrapper">
            {this.props.assetContactList ? (
              <SimpleTable 
                {...this.props} 
                headCells={headCells} 
                dataList={this.props.assetContactList}
                confirmMessage={confirmDialogMessages.confirmDeleteContact} 
                confirmDialogCallback = {this.confirmDialogCallback}
                />
            ) : null}
          </div>

简单表组件代码:

    <Fragment>
            <div className={classes.root}>
                <Paper className="assetPaper">
                    {renderTablePagination('top')}
                    <div className={classes.tableWrapper}>
                        { !props.loaderStatus && props.dataList.length === 0 ? (
                            <Fragment>
                                <Table stickyHeader={props.stickyHeader} aria-label="sticky table" className={classes.table}  size={dense ? 'small' : 'medium'}>
                                    {renderEnhancedTableHead()}
                                </Table>
                                <NoRecordFound />
                            </Fragment>
                        ) : props.loaderStatus && props.dataList.length === 0 ? (
                            <Fragment>
                                <Table stickyHeader={props.stickyHeader} aria-label="sticky table" className={classes.table}  size={dense ? 'small' : 'medium'}>
                                    {renderEnhancedTableHead()}
                                </Table>
                                <LoaderComponent />
                            </Fragment>
                        ) : (
                            <Fragment>
                                <Table stickyHeader={props.stickyHeader} aria-label="sticky table" className={classes.table}  size={dense ? 'small' : 'medium'}>
                                    {renderEnhancedTableHead()}
                                    {renderTableBody()}
                                </Table>
                            </Fragment>
                        ) }
                    </div>
                    {renderTablePagination('bottom')}
                </Paper>
            </div>
            <ConfirmDialog itemId={confirmDialogItemId} {...props} />
        </Fragment >

确认对话框的内容

        function ConfirmDialog(props) {

      function handleOk() {
        props.isFlagApiProcessing();
        props.closeConfirmFlag();
        props.confirmDialogCallback(props.itemId)
      }


      const handleClose = ()=>{
        props.closeConfirmFlag();
      }

      return (
        <div>
          <Dialog
            open={props.showFlagConfirmation}
            onClose={handleClose}
            maxWidth="lg"
            aria-labelledby="alert-dialog-title"
            aria-describedby="alert-dialog-description"
            className="confmation-dialog-wrapper"
          >
            <DialogContent className="confirmation-dialog-content-section">
                <ConfimationContent {...props} handleOk={handleOk}/>
            </DialogContent>
          </Dialog>
        </div>
      );
    }

    export const mapStateToProps = (state) => {
      return {
        showFlagConfirmation: state.events.showFlagConfirmation,
        isFlagApiProcessing: state.events.isFlagApiProcessing,
      }
    }

    const mapDispatchToProps = (dispatch) => {
      return {
        closeConfirmFlag: () => {
          dispatch(closeFlagConfirmation())
        },
        isFlagApiProcessing: () => {
          dispatch(isFlagApiProcessing())
        }
      }
    }


    const ConfimationContent = (props) => {
      const { handleOk, closeConfirmFlag, confirmMessage} = props;
      return (
        <Grid container className="confiramation-content-body">
              <Grid item sm={12}>
                <Box className="top-section">
                   <img src={ConfimationAlertSVG} alt="alert-img" />
                </Box>
                <Box className="bottom-section">
                  <Typography variant="subtitle1" gutterBottom>
                    {confirmMessage}
                  </Typography>
                  <Box className="btn-group">
                    <Button className="btn yes-btn" onClick={handleOk}>
                      yes
                    </Button>
                    <Button className="btn cancel-btn" onClick={closeConfirmFlag}>
                      Cancel
                    </Button>
                  </Box>
                </Box>
              </Grid>
        </Grid>
      )
    }


    export default connect(mapStateToProps,mapDispatchToProps)(ConfirmDialog);

请开个玩笑帮助我。

0 个答案:

没有答案