ws "WebSocket is not open: readyState 3 (CLOSED)" in CI
The Node ws library throws "WebSocket is not open: readyState 3 (CLOSED)" when you call .send() after the socket has closed. readyState 3 is CLOSED; the write had nowhere to go.
What this error means
A test throws from ws.send(...) with this message. It flakes because the test sends before the open event, or after the server already closed the connection.
Error: WebSocket is not open: readyState 3 (CLOSED)
at WebSocket.send (node_modules/ws/lib/websocket.js:...)Common causes
send() called before open or after close
The test writes to the socket while it is still connecting (readyState 0) and it later closes, or writes after the peer closed it (readyState 3).
The server closed the connection early
A rejected handshake or an unhandled error on the server closes the socket, and the client's next send hits a CLOSED state.
How to fix it
Send only after the open event
- Wait for
openbefore the firstsend. - Guard sends with a
readyState === WebSocket.OPENcheck. - Handle the
closeanderrorevents so failures are visible, not silent.
ws.on('open', () => ws.send('hello'));
ws.on('error', (e) => done(e));Guard every send with readyState
Never call send blindly; check the socket is OPEN first.
if (ws.readyState === ws.OPEN) ws.send(payload);How to prevent it
- Await the open event before sending in tests.
- Attach close/error handlers so an early close surfaces clearly.
- Guard sends with an OPEN readyState check.