0

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.

Czyzby
  • 2,999
  • 1
  • 22
  • 40

2 Answers2

3

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)
}
  • The Promise support was added in 1.2.20, should work in Mocha, Jasmine, and Jest. This is not a final design, most likely there will be a more convenient way. – Anton Bannykh Feb 16 '18 at 14:50
  • It would be convenient if tests could consume a `done: () -> Unit` callback, similarly to how Mocha solves this. However, I think `Promise`-based approach is the best for now, as it does not require external bindings. – Czyzby Feb 16 '18 at 17:43
0

If you want to test async code, you need to tell the test framework when the test is done. See this answer.

  • Yes, I eventually went with Mocha bindings and using `describe`/`it` to use the `done` callback. – Czyzby Feb 15 '18 at 16:32
  • Note that it's also possible to implement using `Promise`. Make the test return promise and call `resolve` when done with the asserts. – Czyzby Feb 15 '18 at 17:44