我有一个搜索栏组件,它看起来像:
render () {
const { onChangeTextInput } = this.props
return (
<Form
name="searchForm"
ref={(ref) => {
this.searchForm = ref
}}
>
<TextInput
noSpacing
placeholder={t('search')}
name="search"
validate="text"
icon={this.icon}
onChangeTextCallback={() => {
onChangeTextInput(this.searchForm.values)
}}
/>
)
</Form>
)
}
}
我正在使用浅渲染和开 Jest 来运行单元测试来测试以下场景"
- 用户在文本输入中键入一个字符
- 一个回调方法被触发,为用户提供文本作为参数。
我正在运行的测试声明为:
test('SearchBar returns value on text change', () => {
const onChangeFunction = jest.fn()
const obj = shallow(
<SearchBar onChangeTextInput={onChangeFunction} />
)
obj.find('TextInput').props().onChangeTextCallback('h')
expect(onChangeFunction).toHaveBeenCalledWith('h')
})
我收到一个奇怪的错误:
TypeError: Cannot read property 'values' of undefined
51 | icon={this.icon}
52 | onChangeTextCallback={() => {
> 53 | onChangeTextInput(this.searchForm.values)
| ^
54 | }}
55 | />
56 | )
我的 obj.html() 测试转储看起来像:
<Form name="searchForm" if={true}>
<TextInput
noSpacing={true}
placeholder="search"
name="search"
validate="text"
icon={{
$$typeof: Symbol(react.element),
type: [(Function: Icon)],
key: null,
ref: null,
props: {
name: "search",
size: 25,
color: "#00a8ca",
style: { position: "absolute", right: 0, bottom: 7 },
allowFontScaling: false,
type: "MaterialIcons",
if: true,
},
_owner: null,
_store: {},
}}
onChangeTextCallback={[(Function: onChangeTextCallback)]}
value={null}
style={{}}
hasFloatingLabel={true}
numberOfLines={1}
isPassword={false}
if={true}
/>
)
</Form>
这里发生了什么?我有自定义表单,可以通过 refs 给我值。我是否需要做一些事情并可能初始化 Form 组件?请帮忙,我对这些东西比较陌生。
最佳答案
问题
ref
回调未被调用,因此当 onChangeTextCallback()
为 this.searchForm
时 undefined
调用。
详情
来自Callback Refs文档:“当组件挂载时,React 将使用 DOM 元素调用 ref 回调”。
在测试中,您使用的是 shallow()
。浅渲染不会挂载组件,因此永远不会调用 ref
回调。
解决方案
安装组件。由于您已经在使用 Enzyme
,因此您可以使用 mount()
.请注意,“完整的 DOM 呈现要求在全局范围内提供完整的 DOM API”,对于 Jest
,您可以 configure the test environment to use jsdom
.
关于javascript - Jest 测试因 refs 和 Form 而失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52265354/