TL;DR
- On JS one can use
GlobalScope.promise { ... }
.
- But for most use cases the best option is probably to use
runTest { ... }
(from kotlinx-coroutines-test
), which is cross-platform, and has some other benefits over runBlocking { ... }
and GlobalScope.promise { ... }
as well.
Full answer
I'm not sure what things were like when the question was originally posted, but nowadays the standard, cross-platform way to run tests that use suspend
functions is to use runTest { ... }
(from kotlinx-coroutines-test
).
Note that in addition to running on all platforms, this also includes some other features, such as skipping delay
s (with the ability to mock the passage of time).
If for any reason (which is not typical, but might sometimes be the case) it is actually desirable to run the code in the test as it runs in production (including actual delay
s), then runBlocking { ... }
can be used on JVM and Native, and GlobalScope.promise { ... }
on JS. If going for this option, it might be convenient to define a single function signature which uses runBlocking
on JVM and Native, and GlobalScope.promise
on JS, e.g.:
// Common:
expect fun runTest(block: suspend CoroutineScope.() -> Unit)
// JS:
@OptIn(DelicateCoroutinesApi::class)
actual fun runTest(block: suspend CoroutineScope.() -> Unit): dynamic = GlobalScope.promise(block=block)
// JVM, Native:
actual fun runTest(block: suspend CoroutineScope.() -> Unit): Unit = runBlocking(block=block)