@@ -34,12 +34,15 @@ import kotlinx.coroutines.CoroutineScope
3434import kotlinx.coroutines.Dispatchers
3535import kotlinx.coroutines.Job
3636import kotlinx.coroutines.MainScope
37+ import kotlinx.coroutines.TimeoutCancellationException
3738import kotlinx.coroutines.channels.Channel
3839import kotlinx.coroutines.flow.collect
3940import kotlinx.coroutines.flow.takeWhile
4041import kotlinx.coroutines.launch
4142import kotlinx.coroutines.test.TestResult
4243import kotlinx.coroutines.test.runTest
44+ import kotlinx.coroutines.withContext
45+ import kotlinx.coroutines.withTimeout
4346import kotlinx.coroutines.yield
4447import org.w3c.dom.Element
4548import org.w3c.dom.HTMLCanvasElement
@@ -104,13 +107,23 @@ internal interface OnCanvasTests {
104107 ) {
105108 ComposeViewport (viewportContainerId = containerId, configure = configure, content = content)
106109
107- suspendCoroutine { continuation ->
108- // This helps reduce the flakiness.
109- // A potential cause of flakiness: the default Coroutine Dispatcher regularly postpones
110- // the resumption of the tasks in its queue to the next frame.
111- // (it does so to let the event loop run / release the single thread)
112- // I don't expect any issue from doing this, since a test will suspend and won't do anything.
113- window.requestAnimationFrame { continuation.resumeWith(Result .success(it)) }
110+ withContext(Dispatchers .Default ) {
111+ val timeoutDuration = 1 .seconds
112+ try {
113+ // Using withTimeout here for diagnostic. Some flaky tests fail due to timeout. But there is nothing else except this suspend call.
114+ withTimeout(timeoutDuration) {
115+ suspendCoroutine<Unit > { continuation ->
116+ // This helps reduce the flakiness.
117+ // A potential cause of flakiness: the default Coroutine Dispatcher regularly postpones
118+ // the resumption of the tasks in its queue to the next frame.
119+ // (it does so to let the event loop run / release the single thread)
120+ // I don't expect any issue from doing this, since a test will suspend and won't do anything.
121+ window.requestAnimationFrame { continuation.resumeWith(Result .success(Unit )) }
122+ }
123+ }
124+ } catch (e: TimeoutCancellationException ) {
125+ throw AssertionError (" Timed out ($timeoutDuration ) waiting for AnimationFrame" , e)
126+ }
114127 }
115128 }
116129
@@ -159,6 +172,18 @@ internal interface OnCanvasTests {
159172 WebApplicationScope (this ).body()
160173 }
161174 }
175+
176+ suspend fun <T > Channel<T>.receiveWithTimeout (timeout : Duration = 2.seconds): T {
177+ return withContext(Dispatchers .Default ) {
178+ try {
179+ withTimeout(timeout) {
180+ this @receiveWithTimeout.receive()
181+ }
182+ } catch (e: TimeoutCancellationException ) {
183+ throw AssertionError (" Timed out ($timeout ) waiting for value on channel" , e)
184+ }
185+ }
186+ }
162187}
163188
164189internal fun <T > Channel<T>.sendFromScope (value : T , scope : CoroutineScope = MainScope ()) {
0 commit comments