Search code examples
kotlinmocha.jskarma-mochakotlin-interopkotlin-js-interop

How to properly test web socket connection with KotlinJS


I'm unable to test my code that uses a native WebSocket. This is the body of the test function:

val webSocket = WebSocket("ws://localhost:8888")
window.setTimeout({
    assertEquals(WebSocket.OPEN, webSocket.readyState)
}, 1000)

I'm using Karma with Mocha test runner. The following code executes without any errors, but the setTimeout is actually ignored and never executed.

Mocha seems to support setTimeout-based tests with the --delay. However, when I use the flag with client: { mocha: { delay: true } } Karma configuration, the tests just freeze and fail, outputting the following cause message:

Disconnected, because no message in 60000 ms.

What is the correct way to execute tests with setTimeout? If this is tricky, is there any other way I can perform assertions on the WebSocket after it's fully connected? I don't use any Mocha-specific features yet, so I don't mind changing the framework.


Solution

  • Returning Promise from your @Test function should do the trick. Something like:

    @Test fun testWebSocket() = Promise<Unit> { resolve, reject ->
        val webSocket = WebSocket("ws://localhost:8888")
        window.setTimeout({
            assertEquals(WebSocket.OPEN, webSocket.readyState)
            resolve(Unit)
        }, 1000)
    }