Nacho Ruiz Martin
04/17/2024, 2:47 PMcomposeTestRule
from the Main Activity.
I’m using Nav Component in the app and the navigation is working when launched as an app, but it doesn’t when launched as an Android test.
I was so surprised that I created a really simple project reproducing the error and it’s indeed happening there.
Here’s the project: https://github.com/iruizmar/nav-component-ui-test-reproducer
As you can see, the MainActivity
just waits for 1s and then navigates to “screen”. The test is waiting forever. If the app is launched normally, the navigation happens but it doesn’t happen in the test.
What am I missing?
Thanks!Nacho Ruiz Martin
04/17/2024, 2:52 PMChrimaeon
04/17/2024, 3:23 PMStylianos Gakis
04/17/2024, 3:24 PMNacho Ruiz Martin
04/17/2024, 4:44 PMChrimaeon
04/17/2024, 4:54 PMmainClock
from the compose rule.
https://developer.android.com/reference/kotlin/androidx/compose/ui/test/MainTestClockNacho Ruiz Martin
04/17/2024, 5:09 PMNacho Ruiz Martin
04/18/2024, 5:58 AMStylianos Gakis
04/18/2024, 8:04 AMNacho Ruiz Martin
04/18/2024, 8:20 AM@Test
fun test() = runTest {
composeTestRule.awaitIdle()
composeTestRule.runOnIdle {
assert(true)
}
}
It’s not that much, but it requires a bit of knowledge of how the Compose code was written.
For instance, you could do something like:
runTest {
composeTestRule.awaitIdle()
composeTestRule.runOnIdle {
//We are sure this is run on idle,
// but it's on the main thread, so you can't assert with `onNode***`
}
but, as you can see, you should advance the clock manually.
Something even cooler is:
fun test() = runTest { composeTestRule.waitUntilExactlyOneExists(hasText("screen")) composeTestRule.onNodeWithText("screen").performClick()
}
Anyway, this has helped me a lot. Thanks guys! 🫶