What is an alternative for back handling in UI tes...
# compose
j
What is an alternative for back handling in UI tests? Previously I used:
Copy code
Espresso.onView(ViewMatchers.isRoot()).perform(ViewActions.pressBack())
With Compose I'm trying this:
Copy code
val keyEvent = NativeKeyEvent(NativeKeyEvent.ACTION_DOWN, NativeKeyEvent.KEYCODE_BACK)
composeTestRule.onRoot().performKeyPress(KeyEvent(keyEvent))
but getting:
Copy code
KeyEvent can't be processed because this key input node is not active.
If so, you could provide your own
LocalOnBackPressedDispatcher
and your code will use that - then you can just call
onBackPressedDispatcher.onBackPressed()
from your test
Or, since your tests are running in a
ComponentActivity
anyways, you can just retrieve it via
LocalOnBackPressedDispatcherOwner.current!!.onBackPressedDispatcher
inside your
composeTestRule.setContent
Then call
onBackPressed()
on that
j
No, I'm running fairly full-setup UI tests - i.e. I'm rather testing compose navigation.
So I'm using
createEmptyComposeRule()
and just accommodating the way the screen was tested for new composer rewrite.
i
Navigation Compose also uses the same
OnBackPressedDispatcher
j
Is there other way to obtain it since I do not have any composable lambda available because there is no setContent for me.
i
Do you have a reference to your activity? If so, then you can get the
onBackPressedDispatcher
directly from the activity (
ComponentActivity
implements
OnBackPressedDispatcherOwner
)
j
Thanks, that works!
Copy code
activity.runOnUiThread {
  val dispatcherOwner = (activity as OnBackPressedDispatcherOwner)
  val dispatcher = dispatcherOwner.onBackPressedDispatcher
  dispatcher.onBackPressed()
}