I'm trying to write some tests asserting the state...
# compose
c
I'm trying to write some tests asserting the state of my snapshot state. It's testing within a ViewModel so it (unfortunately) uses viewModelScope.launch (which i hope doesn't derail the discussion. But essentially, this test should pass, but it doesn't. What's the best way to wait for my snapshotState to return a value to assert upon it?
Copy code
@Test
fun `vm state is right`() {
  runBlocking {
    val myVm = HomeScreenViewModel(FakeGetHomeScreenUseCase())
    myVm.populateItemsWithOneItem()
    assertEquals(1, myVm.state.items.size)
  }
}
My VM:
Copy code
fun populateItemsWithOneItem() {
  viewModelScope.launch {
    state.items.addAll(getHomeScreenUseCase.getItems())
  }
}
z
Wait for whatever dispatcher your coroutine is using to get to idle. If compose-based, use Compose’s runOnIdle, otherwise Espresso.onIdle should work
Espresso.onIdle waits for the main queue to be idle, which is what viewModelScope dispatches to I believe
c
Do you know if I need to be writing androidTests with this or should this work in a unit test? Reason I ask is because I tried in a unit test and was met with
Copy code
FINGERPRINT must not be null
lol. idk what that is
Actually. I guess I'm using dispatchers.main. But I can't really find a way to awaitIdle on the main dispatcher. Maybe im missing something basic here (sorry im still new to testing this stuff)
but it seems pretty basic like I should be able to test this... right?
z
Compose UI’s testing framework uses some hackery to await idle with Robolectric - a combination of Espresso.onIdle and explicitly checking internal compose state. If you’re just waiting for a coroutine launcher on main, I would expect Espresso.onIdle would be enough, but then I would assume you’d need to use the Main dispatcher as well
c
Hm. Still no dice. I guess I'm going to give up here. Really not sure how testing something like this ends up being such a pain. 😭
a
Have you tried injecting your dispatcher? Then you can swap it out for anything
c
Even if I inject my dispatcher, dont I still need to wait somehow?
178 Views