reactjs - 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)
与比较值没有视觉差异任何想法为什么会发生这种情况将不胜感激!
解决方案
您应该根据您的用例使用 mount 或 shallow 来渲染您的组件。
如果要渲染组件,则使用 mount ,其中所有子节点都将渲染到最后一个叶节点。
如果您需要对组件进行深度渲染,请使用 shallow 。
注意:在大多数情况下,您应该使用浅渲染,因为挂载需要很长时间。
推荐阅读
- python - 如何使用 lambda 从 AWS S3 存储中获取特定文件字数?
- javascript - 使用 Ajax 更新 Woocommerce 产品库
- sql - 如何透视 SQL 数据?
- android - 如何模拟用于浓缩咖啡测试的相机输入?
- android - 是否可以在没有 Root 的情况下推送 ADB 系统文件?
- amazon-web-services - 如何在打开图片网址时修复“访问被拒绝”
- validation - 如何在本机反应中验证文本输入以获取最少字符
- matlab - MATLAB:为什么函数不能处理给定日期输入中的错误?
- c# - 在 Service Fabric 服务中启用每个终结点的 gzip 压缩
- unity3d - VR/AR 工具包问题