【发布时间】:2019-02-15 08:01:53
【问题描述】:
我有一个搜索栏组件,看起来像:
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>
)
}
}
我正在使用浅渲染和玩笑来运行单元测试来测试以下场景”
- 用户在文本输入中键入一个字符
- 一个回调方法被触发,它为用户提供文本作为参数。
我正在运行的测试声明为:
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 组件?请帮忙,我对这些东西比较陌生。
【问题讨论】:
标签: javascript reactjs react-native jestjs enzyme