1

I'm automating a test on a search field but typeText() enters the search text much faster than a user so the search field's autocompletion feature doesn't have time to respond after each keystroke.

One solution proposed in Slow down Espresso suggests using IdlingResource but I'm hoping there's a simpler solution.

A similar problem was Espresso - typeText() not working correclty, sometimes letters are missing but that's different because the full text is getting inputted, it's just the code that responds to each typed character isn't given enough time to respond.

How can I force Espresso to type the characters slowly enough into a search field for the autocomplete to have enough time to finish? The autocomplete is tuned to respond to a human's speed of typing.

Michael Osofsky
  • 11,429
  • 16
  • 68
  • 113

1 Answers1

1

To type input into a TextView, we can type one character at a time so any autocompletion logic has time to complete. This simulates a user typing better than inserting a full string of text all at once (which would be more like the user copying and pasting text into the field).

We type the first character with typeText() and the remaining characters with typeTextIntoFocusedView() because typeText() performs a tap on the view before typing to force the view into focus, if the view already contains text this tap may place the cursor at an arbitrary position within the text.

private void typeInputIntoTextView(int textViewId, String text) {
    if (0 != text.length()) {
        Espresso.onView(ViewMatchers.withId(textViewId)).perform(ViewActions.typeText(text.substring(0, 1)));
        for (int i = 1; i < text.length(); i++) {
            Espresso.onView(ViewMatchers.withId(textViewId)).perform(ViewActions.typeTextIntoFocusedView(text.substring(i, i + 1)));
        }
    }
}
Michael Osofsky
  • 11,429
  • 16
  • 68
  • 113