Reputation: 3798
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.
Upvotes: 10
Views: 5123
Reputation: 508
This works for me:
composeTestRule.onAllNodes(isRoot())[0].performKeyPress(
KeyEvent(
android.view.KeyEvent(
android.view.KeyEvent.ACTION_DOWN,
android.view.KeyEvent.KEYCODE_BACK
)
)
)
Upvotes: 3
Reputation: 3798
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.
Upvotes: 13
Reputation: 677
We can use below code to test device back button from composable screen
Espresso.pressBack()
Upvotes: 9