elysiajs / elysia

Ergonomic Framework for Humans

Home Page:https://elysiajs.com

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Unable to Unit Test WebSocket

tnraro opened this issue · comments

What version of Elysia.JS is running?

1.0.27

What platform is your computer?

Linux 5.15.146.1-microsoft-standard-WSL2 x86_64 unknown

What steps can reproduce the bug?

I am unable to unit test the WebSocket. Eden Treaty tries and fails to connect to ws://e.ly/ws.

import Elysia from "elysia"
import { describe, expect, test } from "bun:test"
import { treaty } from "@elysiajs/eden"
import { sleep } from "bun"

describe("WebSocket", () => {
  test("via Elysia.handle", async () => {
    const app = new Elysia().ws("/ws", {})

    const res = await app.handle(new Request("http://e.ly/ws"))
    expect(res.status).toBe(101) // Received: 404
  })

  test("via Eden Treaty", async () => {
    const app = new Elysia().ws("/ws", {})

    const api = treaty(app)

    const client = api.ws.subscribe()
    expect(client.ws.readyState).toBe(client.ws.CONNECTING)
    await sleep(500)
    expect(client.ws.readyState).toBe(client.ws.OPEN) // Received: 3 (CLOSED)
  })
})

What is the expected behavior?

The WebSocket connection is successful and can be tested.

What do you see instead?

The connection will always be closed soon.

Additional information

No response

I would love to see this fixed. Has me at a full stop with a big development project 😅

You have not started the websocket by calling the listen(anyPort) function?

@franszhafran As far as I know, the unit test should be able to test the route without running the actual server. Elysia's unit test documentation also says that it simulates HTTP requests.

Although, there is no information about WebSocket in the document, but it would be beneficial if Elysia could support it.

End-to-end testing is more cumbersome 😢

@tnraro As this documentation page, it is still required to run the server

@franszhafran I haven't tried your suggestion, but if it works, it would be a good workaround.

I think there was some confusion because I put a bug label on this issue. The point of this issue is that we need a way to do unit testing without running the server like other routes.

Yeah as long as I dug out, mocked web socket testing is not supported by Eden. Currently the only possible way is to test a real web socket server. I do not know the framework author decision on this feature. I will try to follow up about this feature.

Yeah for an enterprise project I was not able to use this for the lack of unit testing available.

Otherwise it'd have served its purpose 😀

I currently have a project that heavily depends on websockets. My workaround for this was to create a helper function that started the app on an actual port (4011) in my case and returned an eden treaty. That might work for your use case