How to test a viewmodel that has a mutable state f...
# coroutines
a
How to test a viewmodel that has a mutable state flow collector that doesn't complete.
Copy code
private fun observeForRefreshSignal() {
        viewModelScope.launch {
            refreshSignal.collectLatest {
                updateUiStateAndStateEvents()
            }
        }
}
Getting this error,
Copy code
After waiting for 3s, the test coroutine is not completing, there were active child jobs:
Test code
Copy code
private val testDispatcher = UnconfinedTestDispatcher()
private val testScope = TestScope(testDispatcher)

@Before
fun setUp() {
    viewModel = ScreenViewModel(
        coroutineScope = coroutineScope,
        // other dependencies
    )
}

@Test
fun `initViewModel currentAccount is null`() = runTestWithTimeout {
    // ... Mocking

    editAccountScreenViewModel.initViewModel()

    // ... Assertions
}

private fun runTestWithTimeout(
    block: suspend TestScope.() -> Unit,
) = testScope.runTest(
    timeout = 3.seconds,
) {
    block()
}
Commenting this code, results in successful test (This test does not test this code for now),
Copy code
refreshSignal.collectLatest {
    updateUiStateAndStateEvents()
}
r
You have to collect from the flow , and than manually cancel it
1
Copy code
`val numberFlow = MutableStateFlow(0)
fun addElements() {
    numberFlow.value = 1
    numberFlow.value = 2
    numberFlow.value = 3
}

@Test
fun testNumberFlow() = runTest(UnconfinedDispatcher) {
    val numberList: MutableList = mutableListOf<Int>()
    val listJob = launch { 
        numberFlow.collectLatest { numberList.add(it) }
    }
    
    addElements()
    
    listJob.cancel()
    assert ( numberList.size == 3)
    assert ( numberList[0] == 1)
    assert ( numberList[1] == 2)
    assert ( numberList[2] == 3)
}