使用refs和Form进行jest测试失败

问题描述 投票:2回答:1

我有一个搜索栏组件,如下所示:

  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来运行单元测试来测试以下场景“

  1. 用户在文本输入中键入字符
  2. 触发了一个回调方法,它为用户提供了一个参数文本。

我正在运行的测试表示为:

 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>

这里发生了什么?我有自定义表单,通过引用给我价值。我是否需要执行某些操作并初始化Form组件?请帮助,我对这个东西比较新。

javascript reactjs react-native jestjs enzyme
1个回答
4
投票

问题

ref被调用时,this.searchForm回调没有被调用,所以undefinedonChangeTextCallback()

细节

来自Callback Refs文档:“当组件安装时,React将使用DOM元素调用ref回调”。

在测试中你使用的是shallow()。浅呈现不会挂载组件,因此永远不会调用ref回调。

安装组件。由于您已经在使用Enzyme,您可以使用mount()。请注意,“完整DOM渲染需要在全局范围内提供完整的DOM API”,对于Jest,您可以使用configure the test environment to use jsdom

© www.soinside.com 2019 - 2024. All rights reserved.