验证使用withFormik的handleSubmit时,单击按钮时是否调用了模拟函数

时间:2019-05-07 04:15:26

标签: javascript reactjs jestjs formik

我有一个带有一些输入的简单组件,我试图验证单击按钮后是否调用了模拟函数。

这是我在测试文件中尝试过的内容:

import React from 'react'
import { mount } from 'enzyme'
import AddUser from '../Components/AddUserWithFormik'
import { Router } from 'react-router-dom'
import { createBrowserHistory } from 'history'
import * as Constants from '../actions/actionTypes'

const hist = createBrowserHistory()

describe('AddUser page', () => {
  let wrapper
  const mockFetchDetailsActions = jest.fn()
  const mockHandleCancel = jest.fn()
  const mockHandleInputChangeAction = jest.fn()
  const mockHandleSubmit = jest.fn()
  const match = {
    params: {
      id: '12345'
    }
  }
  const location = {
    pathname: '/add_user',
    search: '',
    hash: '',
    key: 'ph0ovl'
  }
  const user = {
    first_name: '',
    last_name: '',
    email: '',
    email_secondary: '',
    mobile_phone: '',
    work_phone: ''
  }

  beforeEach(() => {
    wrapper = mount(
      <Router history={hist}>
        <AddUser
          match={match}
          location={location}
          user={user}
          handleSubmit={mockHandleSubmit}
          actions={{
            fetchDetailsActions: mockFetchDetailsActions,
            handleCancel: mockHandleCancel,
            handleInputChangeAction: mockHandleInputChangeAction
          }}
        />
      </Router>
    )
  })

  describe('#ComponentsRendered', () => {

    it('verify simulate change on all input elements', () => {
      wrapper
        .find('button')
        .at(0)
        .simulate('click')

      expect(mockHandleSubmit).toHaveBeenCalled()
    })
  })
})


这是我的组成部分:

/* eslint-disable no-invalid-this */
import React, { Fragment } from 'react'
import PropTypes from 'prop-types'
import { withStyles } from '@material-ui/core/styles'
import GridContainer from './Grid/GridContainer'
import GridItem from './Grid/GridItem'
import { TextField } from 'formik-material-ui'
import { Field, Form } from 'formik'
import dashboardStyle from '../styles/dashboardStyle'
import Card from './Card/Card'
import CardBody from './Card/CardBody'
import * as Constants from '../actions/actionTypes'
import SaveAndCancelButtons from './Common/saveAndCancelButtons'

class AddUser extends React.Component {
  componentDidMount () {
    if (this.props.match.params.id) {
      this.props.actions.fetchDetailsActions(Constants.FETCH_DETAILS_API_CALL_REQUEST, this.props.match.params.id)
    } else {
      this.props.actions.handleCancel()
    }
  }

  render () {
    const { classes, isFetching } = this.props
    return (
      <Form>
        <Field
          name="user"
          render={feildProps => (
            <Fragment>
              <GridContainer>
                <GridItem xs={12} sm={12} md={12}>
                  <Card>
                    <h2 className={classes.cardTitleWhite}>Add User</h2>
                    <CardBody isFetching={isFetching}>
                      <GridContainer>
                        <GridItem xs={12} sm={12} md={4}>
                          <Field
                            label="First Name"
                            name={`user.first_name`}
                            className={this.props.classes.textField}
                            margin="normal"
                            variant="outlined"
                            component={TextField}
                          />
                          <Field
                            label="Secondary Email"
                            name={`user.email_secondary`}
                            className={this.props.classes.textField}
                            margin="normal"
                            variant="outlined"
                            component={TextField}
                          />
                        </GridItem>
                        <GridItem xs={12} sm={12} md={4}>
                          <Field
                            label="Last Name"
                            name={`user.last_name`}
                            className={this.props.classes.textField}
                            margin="normal"
                            variant="outlined"
                            component={TextField}
                          />
                          <Field
                            label="Mobile Phone"
                            name={`user.mobile_phone`}
                            className={this.props.classes.textField}
                            margin="normal"
                            variant="outlined"
                            component={TextField}
                          />
                        </GridItem>
                        <GridItem xs={12} sm={12} md={4}>
                          <Field
                            label="Email"
                            name={`user.email`}
                            className={this.props.classes.textField}
                            margin="normal"
                            variant="outlined"
                            component={TextField}
                          />
                          <Field
                            label="Work Phone"
                            name={`user.work_phone`}
                            className={this.props.classes.textField}
                            margin="normal"
                            variant="outlined"
                            component={TextField}
                          />
                        </GridItem>
                      </GridContainer>
                    </CardBody>
                  </Card>
                  <SaveAndCancelButtons
                    handleSave={() => {
                      this.props.handleSubmit()
                    }}
                    routingLink="/people"
                    label="Save"
                  />
                </GridItem>
              </GridContainer>
            </Fragment>
          )}
        />
      </Form>
    )
  }
}

AddUser.propTypes = {
  classes: PropTypes.object.isRequired
}

export default withStyles(dashboardStyle)(AddUser)

这是我的withFormik()包装器:

import { withStyles } from '@material-ui/core/styles'
import { withFormik } from 'formik'
import * as Yup from 'yup'
import AddUser from './AddUser'
import * as Constants from '../actions/actionTypes'

const styles = theme => ({
  textField: {
    width: '100%'
  }
})

const onSave = props => {
  const userDetails = {
    user: props.user
  }
  if (userDetails && userDetails.user.id) {
    props.actions.updateDetailsActions(Constants.UPDATE_USER_API_CALL_REQUEST, userDetails.user.id, userDetails)
  } else {
    props.actions.addNewUserAction(Constants.ADD_USER_API_CALL_REQUEST, userDetails)
  }
}

const validations = Yup.object().shape({
  user: Yup.object().shape({
    first_name: Yup.string().required('Required'),
    last_name: Yup.string().required('Required'),
    email: Yup.string().required('Required')
  })
})

const withFormikWrapper = withFormik({
  validationSchema: validations,
  enableReinitialize: true,
  handleSubmit: props => {
    onSave(props)
  }
})(AddUser)

export default withStyles(styles)(withFormikWrapper)


预期结果:

我希望在发生模拟点击时调用mockHandleSubmit

实际结果:

  expect(jest.fn()).toHaveBeenCalled()

    Expected mock function to have been called, but it was not called.

      123 |       // console.log(wrapper.debug())
      124 | 
    > 125 |       expect(mockHandleSubmit).toHaveBeenCalled()
          |                                ^
      126 |     })
      127 |   })
      128 | })

      at Object.toHaveBeenCalled (src/test/AddUser.test.js:125:32)

这是saveAndCancelButton组件:

import React, { Component } from 'react'
import RoutingButton from './RoutingButton'
import { withStyles } from '@material-ui/core/styles'
import GridContainer from '../Grid/GridContainer'
import GridItem from '../Grid/GridItem'
import ClientContactsStyles from '../../styles/ClientsContactsStyles'
import SaveIcon from '@material-ui/icons/Save'
import Close from '@material-ui/icons/Close'
import classNames from 'classnames'
import Button from '@material-ui/core/Button'

class SaveAndCancelButtons extends Component {
  render () {
    const { classes } = this.props
    const close = <Close />
    return (
      <GridContainer>
        <GridItem xs={12} sm={12} md={6}>
          {this.props.submitButtonProps ? (
            <GridItem xs={12} sm={12} md={6}>
              <Button
                variant="contained"
                size="large"
                className={classes.button}
                onClick={this.props.handleSubmit}
              >
                Submit
              </Button>
            </GridItem>
          ) : null}
        </GridItem>
        <GridItem xs={12} sm={12} md={3}>
          <Button
            variant="contained"
            size="large"
            className={classes.button}
            onClick={this.props.handleSave}
          >
            <SaveIcon
              className={classNames(classes.leftIcon, classes.iconSmall)}
            />
            {this.props.label}
          </Button>
        </GridItem>
        <GridItem xs={12} sm={12} md={3}>
          <RoutingButton
            variant="contained"
            size="large"
            className={classes.button}
            buttonIcon={close}
            routingLink={this.props.routingLink}
            label="Cancel"
          />
        </GridItem>
      </GridContainer>
    )
  }
}

export default withStyles(ClientContactsStyles)(SaveAndCancelButtons)

enter image description here

2 个答案:

答案 0 :(得分:1)

这里的问题是,玩笑功能没有等待formik调用其onSubmit()函数。要解决此问题,请提供“ wait” api。请参见下面的代码。

await wait(() => {
  expect(mockHandleSubmit).toHaveBeenCalled()
});

快乐编码:)

答案 1 :(得分:1)

我不认为调用提交是因为您的用户未通过您的验证。对此进行纠正,并在下面使用以供期盼。

xxxxxx 鉴于您已经在满足上述架构的帖子中省略了测试代码,因此不是解决方案。解决方案是对行动采取期望。无法模拟handleSubmit,因为这由withFormik包装器处理。 xxxxxx

it('verify simulate change on all input elements', async () => {
  wrapper.find('button').at(0).simulate('click')
  await new Promise(resolve=>{
    setTimeout(()=>resolve(),0);
  })
  expect(mockHandleSubmit).toHaveBeenCalled()
})