How to submit a form or press the enter key on an input with react-native-testing-library
Asked Answered
L

1

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.

Landahl answered 4/1, 2021 at 14:26 Comment(2)
are you using Jest? - this might help testing-library.com/docs/react-testing-library/example-introMatless
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.Landahl
S
10

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.

Sallysallyann answered 4/1, 2021 at 17:23 Comment(3)
This actually worked for me!!! Thanks very much. Tried several different things and none of them worked, until now.Landahl
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 reactnative.dev/docs/textinput or in the link you have sent above. Could you give the source, how you have found solution?Korykorzybski
The name of the handler is 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.Sallysallyann

© 2022 - 2024 — McMap. All rights reserved.