Ack*_*man 3 javascript reactjs jestjs react-native enzyme
我有一个搜索栏组件,看起来像:
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>
)
}
}
Run Code Online (Sandbox Code Playgroud)
我正在使用浅渲染和玩笑来运行单元测试以测试以下情况”
我正在运行的测试表示为:
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')
})
Run Code Online (Sandbox Code Playgroud)
我收到一个奇怪的错误说明:
TypeError: Cannot read property 'values' of undefined
51 | icon={this.icon}
52 | onChangeTextCallback={() => {
> 53 | onChangeTextInput(this.searchForm.values)
| ^
54 | }}
55 | />
56 | )
Run Code Online (Sandbox Code Playgroud)
我的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>
Run Code Online (Sandbox Code Playgroud)
这是怎么回事 我有自定义表单,可通过引用为我提供价值。我是否需要做一些事情,也许初始化Form组件?请帮助,我对这个东西比较陌生。
问题
该ref回调是没有得到调用,所以this.searchForm是undefined时候onChangeTextCallback()被调用。
细节
从Callback Refs文档中:“当组件安装时,React将使用DOM元素调用ref回调。”
在测试中,您正在使用shallow()。浅渲染不会挂载组件,因此ref永远不会调用该回调。
解
安装组件。由于您已经在使用Enzyme,因此可以使用mount()。请注意,“完整的DOM呈现要求在全局范围内可用完整的DOM API”,因为Jest您可以配置要使用的测试环境jsdom。