Skip to content

Commit

Permalink
fix: forward server errors to WebSocket client (#507)
Browse files Browse the repository at this point in the history
  • Loading branch information
kettanaito authored Feb 15, 2024
1 parent c8bd480 commit b5d0663
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 1 deletion.
8 changes: 8 additions & 0 deletions src/interceptors/WebSocket/WebSocketServerConnection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,14 @@ export class WebSocketServerConnection {
this.transport.onIncoming(event)
})

// Forward server errors to the WebSocket client as-is.
// We may consider exposing them to the interceptor in the future.
ws.addEventListener('error', () => {
this.mockWebSocket.dispatchEvent(
bindEvent(this.mockWebSocket, new Event('error'))
)
})

this.realWebSocket = ws
}

Expand Down
16 changes: 15 additions & 1 deletion test/modules/WebSocket/exchange/websocket.server.connect.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
/**
* @vitest-environment node-with-websocket
*/
import { it, expect, beforeAll, afterEach, afterAll } from 'vitest'
import { vi, it, expect, beforeAll, afterEach, afterAll } from 'vitest'
import { WebSocketServer } from 'ws'
import { DeferredPromise } from '@open-draft/deferred-promise'
import { WebSocketInterceptor } from '../../../../src/interceptors/WebSocket'
Expand Down Expand Up @@ -104,3 +104,17 @@ it('closes the actual server connection when the client closes', async () => {
expect(ws.readyState).toBe(WebSocket.CLOSED)
expect(realWebSocket?.readyState).toBe(WebSocket.CLOSING)
})

it('throw an error when connecting to a non-existing server', async () => {
interceptor.once('connection', ({ server }) => {
server.connect()
})

const errorListener = vi.fn()
const ws = new WebSocket('ws://localhost:9876')
ws.onerror = errorListener

await vi.waitFor(() => {
expect(errorListener).toHaveBeenCalledTimes(1)
})
})

0 comments on commit b5d0663

Please sign in to comment.