开玩笑的测试失败与引用和窗体 [英] jest test fails with refs and Form
问题描述
我有一个搜索栏组件,看起来像:
I have a search bar component which looks like:
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>
)
}
}
我正在使用浅层渲染和玩笑来运行单元测试以测试以下情况"
I am using a shallow render and jest to run a unit test to test the following scenario"
- 用户在文本输入中输入字符
- 触发回调方法,该方法为用户提供文本作为参数.
我正在运行的测试表示为:
The test I am running is stated as:
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')
})
我收到一个奇怪的错误说明:
I getting a weird error stating :
TypeError: Cannot read property 'values' of undefined
51 | icon={this.icon}
52 | onChangeTextCallback={() => {
> 53 | onChangeTextInput(this.searchForm.values)
| ^
54 | }}
55 | />
56 | )
我的obj.html()测试转储看起来像:
My obj.html() dump for the test looks like:
<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>
这是怎么回事?我有自定义表单,可通过引用为我提供价值.我是否需要做一些事情,也许初始化Form组件?请帮忙,我对这个东西还比较陌生.
what is happening here? I have custom form that gives me values through refs. Do I need to do something and maybe initialize the Form component? please help, I am relatively new to this stuff.
推荐答案
问题
没有调用ref
回调,因此在调用onChangeTextCallback()
时this.searchForm
是undefined
.
The ref
callback isn't getting called so this.searchForm
is undefined
when onChangeTextCallback()
is invoked.
详细信息
从回调参考文档中:反应安装组件时,将使用DOM元素调用ref回调."
From the Callback Refs docs: "React will call the ref callback with the DOM element when the component mounts".
在测试中,您正在使用shallow()
.浅渲染不会挂载组件,因此不会调用ref
回调.
In the test you are using shallow()
. Shallow rendering does not mount the component so the ref
callback is never called.
解决方案
安装组件.由于您已经在使用Enzyme
,因此可以使用 mount()
.请注意,完整的DOM呈现要求在全局范围内必须有完整的DOM API",对于Jest
,您可以配置测试环境以使用jsdom
.
Mount the component. Since you are already using Enzyme
you can use mount()
. Note that "full DOM rendering requires that a full DOM API be available at the global scope", for Jest
you can configure the test environment to use jsdom
.
这篇关于开玩笑的测试失败与引用和窗体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!