Javascript jest测试因引用和表单而失败
我有一个搜索栏组件,看起来像:Javascript jest测试因引用和表单而失败,javascript,reactjs,react-native,jestjs,enzyme,Javascript,Reactjs,React Native,Jestjs,Enzyme,我有一个搜索栏组件,看起来像: render () { const { onChangeTextInput } = this.props return ( <Form name="searchForm" ref={(ref) => { this.searchForm = ref }} > <TextInput noSpacin
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>
)
}
}
<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>
测试的My obj.html()转储如下所示:
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>
)
}
}
<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>
)
这里发生了什么?我有一个自定义表单,它通过引用为我提供值。我需要做些什么,或者初始化表单组件吗?请帮帮我,我对这些东西还比较陌生。问题
调用onChangeTextCallback()
时,ref
回调未被调用,因此this.searchForm
是未定义的
详细信息
从文档中可以看到:“当组件装载时,React将使用DOM元素调用ref回调”
在测试中,您使用的是shallow()
。浅层渲染不会装载组件,因此永远不会调用ref
回调
解决方案
安装组件。由于您已经在使用酶
,因此可以使用。请注意,“完整的DOM呈现要求在全局范围内提供完整的DOM API”,对于Jest
您可以。您能告诉我如何以及在何处使用mount吗?我不知道;我不相信jsdom能与来自“酶”的react nativeimport{mount}一起工作代码>而不是从“酶”导入{shall}
,然后调用mount()
,而不是shallow()
。要在测试中使用jsdom
,可以在测试文件的顶部添加@jest-environment
docblock forjsdom
jsdom
只需将DOM API添加到全局范围中,即可与react native配合使用。感谢您现在尝试:)嘿,感谢您让它工作起来。回答:尝试了不同的方法。