【问题标题】:How to unit-test Kotlin-JS code with coroutines?如何使用协程对 Kotlin-JS 代码进行单元测试?
【发布时间】:2017-12-23 22:14:09
【问题描述】:

我创建了一个多平台 Kotlin 项目(JVM 和 JS),声明了一个预期的类并实现了它:

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

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

现在我正在尝试使用kotlin.test 进行单元测试,而对于 JVM 平台,我只需像这样使用runBlocking

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

如果没有runBlocking,如何在JS平台上重现类似的功能?

【问题讨论】:

    标签: kotlin kotlin-coroutines kotlin-js


    【解决方案1】:

    Mb 已经晚了,但是有开放的 issue 用于增加在 js-tests 中使用 suspend 函数的可能性(该函数将透明地转换为 promise)

    解决方法

    可以在通用代码中定义:

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

    在JVM中实现

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

    在 JS 中使用

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

    【讨论】:

    • 我认为您的代码中有错字,但这个想法似乎不错,谢谢!
    • 我正在努力让 JS 工作,到底是什么错字?
    • 这很好用,但是由于所有测试都是同时启动的(我认为?),当你有很多慢速测试时,它们会超过两秒超时。有什么办法可以修改这个,所以没有超时问题?
    猜你喜欢
    • 2018-05-13
    • 2018-04-20
    • 2018-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-16
    • 2020-04-24
    • 2020-05-07
    相关资源
    最近更新 更多