【问题标题】:How to submit a form or press the enter key on an input with react-native-testing-library如何使用 react-native-testing-library 提交表单或在输入上按 enter 键
【发布时间】:2021-04-10 08:14:46
【问题描述】:

我有以下问题:我需要测试是否在我的测试中调用了某个函数,但要正确测试它,我需要按 Enter 键或提交表单,但它似乎没有按预期工作。我已经尝试过以下方法:

fireEvent.keyDown(input, { key: 'Enter', code: 'Enter' });
fireEvent.submit(input);

触发我的组件的onSubmitEditing 属性的唯一方法是按 Enter 键。

这是我要测试的代码:

<Input placeholder="Cirurgião"
    testID='input_buscaCirurgiao_index'
    value={this.state.text}
    autoCorrect={false}
    keyboardType={(Platform.OS === 'android') ? 'visible-password' : 'default'}
    onChangeText={(item) => this.setState({ text: item })}
    onSubmitEditing={() => { this._searchPressingEnter() }} // i need to test this
    autoCapitalize='none' 
/>

这是_searchPressingEnter 函数的代码:

_searchPressingEnter() {
    Keyboard.dismiss()

    let item = this.state.text

    this._buscarCirurgioes(item)
}

一旦按下 Enter 键,_searchPressingEnter 函数就会被调用,从而触发 onSubmitEditing 属性。

【问题讨论】:

标签: react-native unit-testing react-testing-library react-native-testing-library


【解决方案1】:

在您的测试用例中,您可以触发 submitEditing 事件。

// Assuming `input` is your text input element
fireEvent(input, 'submitEditing')

有关触发事件检查的更多详细信息:https://callstack.github.io/react-native-testing-library/docs/api#fireevent

【讨论】:

  • 这实际上对我有用!!!非常感谢。尝试了几种不同的方法,但直到现在都没有奏效。
  • 不知道为什么,但在我的例子中,我得到了no handler function found for event: "submitEditing"。我的@testing-library/react-native 是版本"^7.2.0"。另外我不确定为什么它被称为input 而不是TextInput 元素。我在reactnative.dev/docs/textinput 或您在上面发送的链接中找不到submitEdditing。您能否提供来源,您是如何找到解决方案的?
  • 处理程序的名称是onSubmitEditingfireEvent(input, 'submitEditing') 将在TextInput 元素上触发该事件。来源是我在答案中提供的链接 - 您可以触发 fireEvent API 中存在的 any 事件。
猜你喜欢
  • 2020-04-09
  • 1970-01-01
  • 2018-09-19
  • 2020-05-09
  • 2020-10-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-27
相关资源
最近更新 更多