am writing tests for my `ViewModel` that exposes s...
# android
m
am writing tests for my
ViewModel
that exposes state with
StateFlow
. I want to test that it emits
Loading
state and than starting data fetching process from
init
block. when I provide fake API I can’t catch
Loading
state because data is fetched immediately and
Success
state is emitted. how to test that
Loading
comes first followed by
Success
?
a
Provide a fake that doesn't complete until you tell the fake to complete, then you can check for loading, advance the fake, then check that the loaded data is available
3
m
can you maybe link to some example for this?
s
Usually i'll do something like this
Copy code
val stateList: MutableList<UiState> = mutableListOf()

            val job = launch {
                uiStateFlow.toList(stateList)
            }

            // do thing under test
            
            stateList.size shouldEqual 2
            stateList.first() shouldEqual Loading
            stateList[1] shouldEqual Success
m
this runs forever
and where exactly should I call
toList()
f
It runs forever because you need to cancel the job after doing the thing under test
2
m
thanks everyone
d
For testing flows use turbine https://github.com/cashapp/turbine