'Turbain and CoroutineTest with delay throws TimeoutCancellationException

I am trying to test a flow with a delay by using Turbain and CoroutineTest library. Does anybody know What I am missing here?

    @Test
    fun test(){
        val flow = flow<Int> {
            emit(1)
            delay(1000)
            emit(2)
        }

        runBlockingTest {
            flow.test(Duration.INFINITE) {
                expectItem()
                expectItem()
                expectComplete()
            }
        }
    }

Here is the error I am getting.

kotlinx.coroutines.TimeoutCancellationException: Timed out waiting for 9223372036854775807 ms


Solution 1:[1]

use cancel() instead of cancelAndIgnoreRemainingEvents() to Cancel collecting events from the source Flow and ignore any events which have already been received. Calling this function will exit the test block. for more info check here

        @Test
        fun test(){
            val flow = flow<Int> {
                emit(1)
                delay(1000)
                emit(2)
            }
    
            runBlockingTest {
                flow.test(Duration.INFINITE) {
                    expectItem()
                  // verify using Assertions or whatever you want
                    cancel() //to cancel the flow
                }
            }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1