Zach
10/14/2022, 7:25 PMstateFlow
that combines two snapshotFlow
that works when running on device, but when I attempt to unit test with turbine, it never emits more than once. Am I doing something wrong or am I going down the wrong path?
fun validInput() = runTest {
viewModel.screenState.test {
assertEquals(awaitItem(), EnterNameScreenState.EnterNameLoadingResults) // passes
viewModel.firstNameInputValidation("test")
// fails, waited too long
assertEquals(awaitItem(), EnterNameScreenState.EnterNameLoadedResults(InputWrapper(value = "test"), InputWrapper(), false)).
}
}
Zach
10/14/2022, 7:25 PMprivate var firstNameState by savedStateHandle.saveable { mutableStateOf(InputWrapper()) }
private var lastNameState by savedStateHandle.saveable { mutableStateOf(InputWrapper()) }
val screenState: StateFlow<EnterNameScreenState> = combine(
snapshotFlow { firstNameState },
snapshotFlow { lastNameState },
) { firstName, lastName ->
flowOf<EnterNameScreenState>(
EnterNameScreenState.EnterNameLoadedResults(
firstName = firstName,
lastName = lastName,
continueButtonEnabled = isContinueEnabled(firstName, lastName)
)
)
}
.flatMapLatest { it }
.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5000L),
initialValue = EnterNameScreenState.EnterNameLoadingResults
)
MR3Y
10/14/2022, 9:15 PMStateFlow
is a little bit different from testing cold flows, you have to explicitly emit new values inside your test { ... }
and in turn it would be collected by turbine's channel, and received from awaitItem()
. take a look at https://github.com/cashapp/turbine#hot-flowsZach
10/14/2022, 9:17 PMemit
inside the test block?Zach
10/14/2022, 9:21 PMsnapshotFlow
thing.MR3Y
10/14/2022, 9:23 PMemit
a new value should just workZach
10/14/2022, 10:10 PMKeith Mayoral
10/23/2022, 5:32 AMKeith Mayoral
10/23/2022, 5:35 AMZach
10/24/2022, 2:51 PMclass MainDispatcherExtension(
val testDispatcher: TestDispatcher = UnconfinedTestDispatcher(),
) : AfterEachCallback, BeforeEachCallback {
override fun beforeEach(context: ExtensionContext?) {
Dispatchers.setMain(testDispatcher)
}
override fun afterEach(context: ExtensionContext?) {
Dispatchers.resetMain()
}
}
Zach
10/24/2022, 2:52 PM