diff --git a/lib/web/websocket/websocket.js b/lib/web/websocket/websocket.js index 483b8c9f189..85e83b2296d 100644 --- a/lib/web/websocket/websocket.js +++ b/lib/web/websocket/websocket.js @@ -471,6 +471,8 @@ class WebSocket extends EventTarget { } if (!this.#handler.wasEverConnected) { + this.#handler.readyState = states.CLOSED + // If the WebSocket connection could not be established, it is also said // that _The WebSocket Connection is Closed_, but not _cleanly_. fireEvent('close', this, (type, init) => new CloseEvent(type, init), { diff --git a/test/websocket/issue-3697-2399493917.js b/test/websocket/issue-3697-2399493917.js new file mode 100644 index 00000000000..de1342da4ae --- /dev/null +++ b/test/websocket/issue-3697-2399493917.js @@ -0,0 +1,15 @@ +'use strict' + +const { test } = require('node:test') +const { WebSocket } = require('../..') +const { tspl } = require('@matteo.collina/tspl') + +// https://github.com/nodejs/undici/issues/3697#issuecomment-2399493917 +test('closing before a connection is established changes readyState', async (t) => { + const { completed, strictEqual } = tspl(t, { plan: 1 }) + + const ws = new WebSocket('wss://example.com/non-existing-url') + ws.onclose = () => strictEqual(ws.readyState, WebSocket.CLOSED) + + await completed +})