8

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?

dazza5000
  • 5,339
  • 6
  • 34
  • 67
egor.zhdan
  • 4,185
  • 5
  • 38
  • 50

1 Answers1

5

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() } 
kurt
  • 1,378
  • 1
  • 11
  • 22
  • I think you have a typo in the code, but the idea seems fine, thanks! – egor.zhdan May 10 '18 at 11:19
  • I'm struggling to get the JS one to work, what exactly was the typo? – Andrew Steinmetz Jul 08 '20 at 06:45
  • This works fine, but since all tests are started concurrently (I think?), when you have many slow tests they exceed the two seconds timeout. Is there any way to modify this so there's no timeout issues? – CLOVIS Dec 21 '20 at 15:46