6

I have the following problem: I need to test if a function is being called on my test, but to test it properly I need to press enter or submit the form, and it doesn't seem to work as intended. I've already tried the following:

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

The only way to trigger the onSubmitEditing prop of my component is by pressing the Enter key.

Here's the code I'm trying to test:

<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' 
/>

Here's the code for the _searchPressingEnter function:

_searchPressingEnter() {
    Keyboard.dismiss()

    let item = this.state.text

    this._buscarCirurgioes(item)
}

Once the Enter key has been pressed, the _searchPressingEnter function should be called, thus triggering the onSubmitEditing prop.

juliomalves
  • 42,130
  • 20
  • 150
  • 146
disconnectedLynx
  • 101
  • 1
  • 11
  • are you using Jest? - this might help https://testing-library.com/docs/react-testing-library/example-intro/ – Suresh Thayu Jan 04 '21 at 15:33
  • Yeah, I could simply spy on the function and verify if it is being called, but for it to be called, I need to submit the form by pressing enter. Clicking on the input won't trigger onSubmitEditing. – disconnectedLynx Jan 04 '21 at 17:03

1 Answers1

9

In your test case you can fire the submitEditing event.

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

For more details on triggering events check: https://callstack.github.io/react-native-testing-library/docs/api#fireevent.

juliomalves
  • 42,130
  • 20
  • 150
  • 146
  • 1
    This actually worked for me!!! Thanks very much. Tried several different things and none of them worked, until now. – disconnectedLynx Jan 04 '21 at 17:30
  • Not sure why, but in my example, I have got `no handler function found for event: "submitEditing"`. My `@testing-library/react-native` is ver `"^7.2.0"`. Also I'm not sure why it is called `input` not `TextInput` element. And I couldn't find `submitEdditing` in https://reactnative.dev/docs/textinput or in the link you have sent above. Could you give the source, how you have found solution? – Lukkar Apr 20 '21 at 12:34
  • The name of the handler is [onSubmitEditing](https://reactnative.dev/docs/textinput#onsubmitediting), `fireEvent(input, 'submitEditing')` will trigger that event on the `TextInput` element. The source is the link I provide in the answer - you can fire _any_ event present in the `fireEvent` API. – juliomalves Apr 20 '21 at 13:37