icerockdev / moko-test

Test utilities for mobile (android & ios) Kotlin Multiplatform development
https://moko.icerock.dev/
Apache License 2.0
11 stars 1 forks source link

Endless join of waitChildrenCompletion with TestViewModelScopeRule #23

Open Tetraquark opened 2 years ago

Tetraquark commented 2 years ago

If some inheritor of ViewModel has any endless collectors of Flow (e.g. launch coroutine in init block for some Flow from abstract repository or collect data using extension asLiveData from moko-mvvm), then waitChildrenCompletion will start endless join of that endless collector coroutines. So, the test will never end.

Tetraquark commented 2 years ago

Workaround using withTimeout:

fun CoroutineScope.waitChildrenCompletion() = runBlocking {
    val job = this@waitChildrenCompletionWithTimeout.coroutineContext[Job]
    val children = job?.children.orEmpty().toList()
    children.forEach {
        try {
            withTimeout(100) {
                it.join()
            }
        } catch (timeOutEx: TimeoutCancellationException) {}
    }
}