-
-
Notifications
You must be signed in to change notification settings - Fork 158
Expand file tree
/
Copy pathwebsocket.connection.error.test.ts
More file actions
50 lines (40 loc) · 1.28 KB
/
websocket.connection.error.test.ts
File metadata and controls
50 lines (40 loc) · 1.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
// @vitest-environment node-with-websocket
import { vi, it, expect, beforeAll, afterEach, afterAll } from 'vitest'
import { WebSocketInterceptor } from '../../../../src/interceptors/WebSocket'
const interceptor = new WebSocketInterceptor()
beforeAll(() => {
interceptor.apply()
})
afterEach(() => {
interceptor.removeAllListeners()
})
afterAll(() => {
interceptor.dispose()
})
it('simulates connection error by throwing inside the "connection" listener', async () => {
interceptor.on('connection', () => {
throw new Error('Mocked connection error')
})
const socket = new WebSocket('wss://example.com')
const openListener = vi.fn()
const closeListener = vi.fn()
const errorListener = vi.fn()
socket.onopen = openListener
socket.onerror = errorListener
socket.onclose = closeListener
await vi.waitFor(() => {
expect(errorListener).toHaveBeenCalledOnce()
})
expect(openListener).not.toHaveBeenCalled()
expect(closeListener).toHaveBeenCalledOnce()
expect(closeListener).toHaveBeenCalledWith(
expect.objectContaining({
type: 'close',
// Mark the closure as a server error.
code: 1011,
// Must include the error as the closure reason.
reason: 'Mocked connection error',
})
)
expect(socket.readyState).toBe(WebSocket.CLOSED)
})