8

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.

Oliver Metz
  • 2,712
  • 2
  • 20
  • 32

3 Answers3

9

I ended up using the ActivityScenarioRule:

composeTestRule.activityRule.scenario.onActivity { activity ->
   activity.onBackPressedDispatcher.onBackPressed()
}

Not sure if this is the right way to do it but it works.

EDIT: As pointed out correctly by LN-12 you should be using the onBackPressedDispatcher to support API 33's predictive back gestures.

Oliver Metz
  • 2,712
  • 2
  • 20
  • 32
  • `activity.onBackPressed()` is deprecated. You should now use `activity.onBackPressedDispatcher.onBackPressed()`. – LN-12 Oct 18 '22 at 06:28
4

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

Espresso.pressBack()
Chait
  • 537
  • 6
  • 15
  • Works and is so much cleaner. Thanks! Don't know how I missed this one. – Oliver Metz Oct 02 '22 at 23:14
  • 1
    Keep in mind, this solution doesn't work on Firebase Test labs (Tested on Pixel 5 physical device). @OliverMetz's solution works in all the cases. – Karthik Jan 09 '23 at 17:02
-1

This works for me:

composeTestRule.onAllNodes(isRoot())[0].performKeyPress(
            KeyEvent(
                android.view.KeyEvent(
                    android.view.KeyEvent.ACTION_DOWN,
                    android.view.KeyEvent.KEYCODE_BACK
                )
            )
        )
prateek
  • 440
  • 4
  • 12