android-jetpack-composeandroid-jetpack-compose-testing

Jetpack Compose back button press in automation test


What is the recommended way to trigger a back button press in a jetpack compose test (running on a real device)?

I'm trying:

@get:Rule()
val composeTestRule = createAndroidComposeRule(MyActivity::class.java)

@Test
fun test() {
    // Here would be some setup code, assertions and navigating into a second screen
     
    // Navigate back to previous screen
    composeTestRule.onRoot().performKeyPress(KeyEvent(NativeKeyEvent(0, KeyEvent.KEYCODE_BACK)))

    // continue... 
}

But I get the error:

java.lang.IllegalStateException: KeyEvent can't be processed because this key input node is not active.

I don't have any special logic for the key presses / navigation and only use out-of-the box functionality of the navigation compose library.


Solution

  • We can use below code to test device back button from composable screen

    Espresso.pressBack()