Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unit-test Kotlin-JS code with coroutines?

I've created a multi-platform Kotlin project (JVM & JS), declared an expected class and implemented it:

// Common module:
expect class Request(/* ... */) {
    suspend fun loadText(): String
}

// JS implementation:
actual class Request actual constructor(/* ... */) {
    actual suspend fun loadText(): String = suspendCoroutine { continuation ->
        // ...
    }
}

Now I'm trying to make a unit test using kotlin.test, and for the JVM platform I simply use runBlocking like this:

@Test
fun sampleTest() {
    val req = Request(/* ... */)
    runBlocking { assertEquals( /* ... */ , req.loadText()) }
}

How can I reproduce similar functionality on the JS platform, if there is no runBlocking?

like image 651
egor.zhdan Avatar asked Dec 23 '17 22:12

egor.zhdan


1 Answers

Mb it's late, but there are open issue for adding possibility to use suspend functions in js-tests (there this function will transparent convert to promise)

Workaround:

One can define in common code:

expect fun runTest(block: suspend () -> Unit)

that is implemented in JVM with

actual fun runTest(block: suspend () -> Unit) = runBlocking { block() }

and in JS with

actual fun runTest(block: suspend () -> Unit): dynamic = promise { block() } 
like image 167
kurt Avatar answered Nov 03 '22 13:11

kurt