首页 > 解决方案 > ReactWrapper 只能包装有效元素(material-ui - 酶)

问题描述

我正在为组件编写测试以测试其功能之一,但出现错误:ShallowWrapper can only wrap valid elements

组件文件如下——TextInput.js:

  /* eslint-disable react/require-default-props */
import React from 'react'
import PropTypes from 'prop-types'
import { InputLabel, TextField } from '@material-ui/core'

const TextInput = ({
  name, label, onChange, placeholder, value, error, optional = false, isDisable = false, t,
}) => (
  <>
    {label ? (
      <InputLabel htmlFor={name} className="default-style_label">
        {label}
        {' '}
        {optional && <span className="optional">{`(${t('application.optional')})`}</span>}
      </InputLabel>
    ) : ''}
    <TextField
      type="text"
      name={name}
      placeholder={placeholder}
      value={value}
      // isRequired={isRequired}
      disabled={isDisable}
      onChange={onChange}
      error={error && true}
      helperText={error}
      variant="outlined"
      className="default-style_input"
    />
  </>
)

TextInput.propTypes = {
  name: PropTypes.string.isRequired,
  label: PropTypes.string,
  onChange: PropTypes.func.isRequired,
  placeholder: PropTypes.string,
  value: PropTypes.string,
  error: PropTypes.string,
  optional: PropTypes.bool,
  isDisable: PropTypes.bool,
  t: PropTypes.func,
}

export default TextInput

测试文件

   /* eslint-disable no-undef */
import React from 'react'
import { shallow, mount } from 'enzyme'
import TextInput from '../TextInput'

function createTestProps(props) {
  return {
    // common props
    name: 'test',
    label: 'foo',
    value: 'bar',
    onChange: jest.fn(),
    // allow to override common props
    ...props,
  }
}

describe('rendering', () => {
  describe('<TextInput>', () => {
    let wrapper
    let instance
    beforeEach(() => {
      const props = createTestProps()
      wrapper = mount(shallow(<TextInput {...props} />)).get(0)
      instance = wrapper.instance()
    })

    afterEach(() => {
      jest.clearAllMocks()
    })

    it('should be rendered', () => {
      const content = wrapper.find('input').at(1)
      console.debug(content.debug())
      console.log(instance)
      expect(content.value).toBe('bar')
    })
  })
})

问题是我的测试在从中删除 mount 时失败

wrapper = mount(shallow(<TextInput {...props} />)).get(0)

与比较值没有视觉差异任何想法为什么会发生这种情况将不胜感激!

标签: reactjsjestjsmaterial-uienzyme

解决方案


您应该根据您的用例使用 mount 或 shallow 来渲染您的组件。

  • 如果要渲染组件,则使用 mount ,其中所有子节点都将渲染到最后一个叶节点。

  • 如果您需要对组件进行深度渲染,请使用 shallow 。

注意:在大多数情况下,您应该使用浅渲染,因为挂载需要很长时间。


推荐阅读