How to test Websocket Client with Jest and react-testing-library
I am not sure if this is the right way or not. But this works for me,
global.sendMsg = null; global.WebSocket = class extends WebSocket { constructor(url) { super("wss://test"); global.sendMsg = null } addEventListener(event, cb) { if (event === "open") { cb(); } else if(event === "message") { global.sendMsg = cb; } } }; test("testing message",() => { render(<LiveChat />); global.sendMsg({data:"test-msg"}); expect.... })
Basically, I overwrote the WebSocket class and stored the message event callback to a constant, and trigger it on the tests to imitate the server message.