繁体   English   中英

使用 JEST 测试由 withFormik() 包装时呈现的简单组件

[英]Testing a simple component is rendered when wrapped by withFormik() using JEST

我有一个带有一些输入和下拉元素的简单组件,我正在尝试测试这些元素是否已呈现。 通过在我的期望语句中找到元素“输入”。

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

import React from 'react'
import { shallow } from 'enzyme'
import AddUser from '../Components/AddUser'

describe('AddUser', () => {
  let wrapper
  let mockFetchDetailsActions
  let mockHandleCancel
  const match = {
    params: { id: '1212212' }
  }
  beforeEach(() => {
    mockFetchDetailsActions = jest.fn()
    mockHandleCancel = jest.fn()
    wrapper = shallow(
      <AddUser
        match={match}
        actions={{
          fetchDetailsActions: mockFetchDetailsActions,
          handleCancel: mockHandleCancel
        }}
      />
    )
  })

  describe('Component rendered', () => {
    it('Elements rendered correctly', () => {
      expect(wrapper.find('input').length).toBe(6)
    })
  })
})

这是我的组件:

/* 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()
    }
  }

  handleChange = name => event => {
    this.props.actions.handleInputChangeAction(name, event.target.value)
  }

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

  handleCancel = () => {
    this.props.history.push('/admin_console')
    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.onSave()
                    }}
                    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'

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

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

const withFormikWrapper = withFormik({
  validationSchema: validations,
  enableReinitialize: true
})(AddUser)

export default withStyles(styles)(withFormikWrapper)

预期结果:

找到 6 个元素。

实际结果:

 AddUser › Component rendered › Elements rendered correctly

    expect(received).toBe(expected) // Object.is equality

    Expected: 6
    Received: 0

      26 |   describe('Component rendered', () => {
      27 |     it('Elements rendered correctly', () => {
    > 28 |       expect(wrapper.find('input').length).toBe(6)
         |                                            ^
      29 |     })
      30 |   })
      31 | })

mount而不是shallow试试这个。

我能够通过使用mount使其工作,并且还从withFormikWrapper()导入组件,而不是从它自己的导入。

在测试文件中:

前:

从 '../Components/AddUser' 导入 AddUser

现在:

从'../Components/AddUserWithFormik' 导入 AddUser

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM