unit-testingandroid-jetpack-compose

How to perform keyboard delete button in automation test in jetpack compose


For a custom edit text made in Jetpack compose, I want to test the delete button from the keyboard, assert the following

  1. clicking the delete button from the keyboard removes the left character from the current cursor position if there is a character present on the left
  2. if there is no character then no changes happen to the Editable text

But I couldn't find the appropriate performXxx() method which does this.


Solution

  • Updated on 5-Nov-2024: As mentioned in the Slack thread, we can focus the field and then perform the key(by using performKeyInput) input by passing the Key.Backspace

    // Moving the cursor at the end of the string
    // so that character can be deleted by Backspace
    onNode(hasSetTextAction()).requestFocus()..performTextInputSelection(TextRange(3, 3))
    onNode(hasSetTextAction()).performKeyInput { pressKey(Key.Backspace) }
    

    Old way: After a few explorations, I found a hack which allowed me to do the testing. Adding the code below with the comments, in case someone wants to try

    CustomTextField(
        value = value,
        onValueChange = onValueChange,
    )
    
    // Performing the text selection at character 2
    onNode(hasSetTextAction()).performTextInputSelection(TextRange(2, 3))
    
    // Setting the selected character to empty which kind of replicates the functionality of the keyboard delete button.
    // This doesn't press the keyboard delete button but good workaround to test the rest of the code
    onNode(hasSetTextAction()).performTextInput("")
    
    // Since the character at the 2nd index is deleted now we can assert that the text is "12"
    onNode(hasSetTextAction(), useUnmergedTree = true).assertTextEquals("12")