forked from schneidmaster/action-cable-react
-
-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathintegration.test.ts
More file actions
216 lines (169 loc) · 8.35 KB
/
Copy pathintegration.test.ts
File metadata and controls
216 lines (169 loc) · 8.35 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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
/**
* End-to-end flows through the public API, against a WebSocket double that
* behaves like a Rails ActionCable server.
*/
import ActionCable from '../lib/action_cable/action_cable'
import type { ChannelParams } from '../lib/action_cable/subscriptions'
import Cable from '../lib/cable'
import ConnectionMonitor from '../lib/action_cable/connection_monitor'
import SubscriptionGuarantor from '../lib/action_cable/subscription_guarantor'
import MockWebSocket from './helpers/mock_web_socket'
const staleThresholdMs = ConnectionMonitor.staleThreshold * 1000
/** Lets the socket finish the work it scheduled: handshake, confirmations... */
function flushSocketWork(): void {
for (let i = 0; i < 3; i++) jest.advanceTimersByTime(1)
}
/** Long enough for the monitor to notice a stale connection and reopen it. */
function letTheMonitorReconnect(): void {
jest.advanceTimersByTime(staleThresholdMs * 4)
flushSocketWork()
}
describe('ActionCable end to end', () => {
beforeEach(() => {
jest.useFakeTimers()
// The monitor jitters its poll interval by up to 100% on the first attempt,
// so without pinning the jitter `letTheMonitorReconnect` advances a fixed
// amount of time past a randomly placed poll and the reconnect assertions
// fail intermittently. Same stub as connection_monitor.test.ts.
jest.spyOn(Math, 'random').mockReturnValue(0)
MockWebSocket.reset()
ActionCable.WebSocket = MockWebSocket
Object.keys(ActionCable._consumers).forEach(key => delete ActionCable._consumers[key])
})
afterEach(() => {
jest.clearAllTimers()
jest.useRealTimers()
jest.restoreAllMocks()
})
function subscribe(channelParams: ChannelParams = { channel: 'ChatChannel', roomId: 1 }) {
const consumer = ActionCable.createConsumer('https://example.com/cable')
const cable = new Cable({})
const events: Array<[string, unknown]> = []
const channel = cable.setChannel('ChatChannel', consumer.subscriptions.create(channelParams))
channel
.on('connected', (payload: unknown) => events.push(['connected', payload]))
.on('disconnected', (payload: unknown) => events.push(['disconnected', payload]))
.on('received', (data: unknown) => events.push(['received', data]))
.on('rejected', () => events.push(['rejected', undefined]))
.on('error', (error: unknown) => events.push(['error', error]))
.on('speak', (data: unknown) => events.push(['speak', data]))
flushSocketWork()
return { consumer, cable, channel, events }
}
it('subscribes, receives and sends messages', () => {
const { consumer, channel, events } = subscribe()
expect(consumer.connection.isOpen()).toBe(true)
expect(MockWebSocket.last.commandsOfType('subscribe')).toHaveLength(1)
expect(events).toContainEqual(['connected', { reconnected: false }])
MockWebSocket.last.broadcast(channel.identifier, { text: 'hello' })
expect(events).toContainEqual(['received', { text: 'hello', action: 'received' }])
channel.perform('speak', { text: 'hi there' })
expect(MockWebSocket.last.commandsOfType('message')[0]).toEqual({
command: 'message',
identifier: channel.identifier,
data: JSON.stringify({ text: 'hi there', action: 'speak' }),
})
channel.unsubscribe()
expect(MockWebSocket.last.commandsOfType('unsubscribe')).toHaveLength(1)
expect(consumer.subscriptions.subscriptions).toHaveLength(0)
})
it('routes messages carrying an action to their own event', () => {
const { channel, events } = subscribe()
MockWebSocket.last.broadcast(channel.identifier, { action: 'speak', text: 'hello!' })
expect(events).toContainEqual(['speak', { action: 'speak', text: 'hello!' }])
expect(events.filter(([name]) => name === 'received')).toHaveLength(0)
})
it('delivers a broadcast to every subscription of the same channel', () => {
const consumer = ActionCable.createConsumer('wss://example.com/cable')
const first = consumer.subscriptions.create('ChatChannel')
const second = consumer.subscriptions.create('ChatChannel')
const received: unknown[] = []
first.on('received', data => received.push(data))
second.on('received', data => received.push(data))
flushSocketWork()
MockWebSocket.last.broadcast(first.identifier, { text: 'hello' })
expect(received).toEqual([
{ text: 'hello', action: 'received' },
{ text: 'hello', action: 'received' },
])
})
it('reconnects a dropped connection and reports the reconnect to subscriptions', () => {
const { consumer, channel, events } = subscribe()
MockWebSocket.last.drop()
expect(events).toContainEqual(['disconnected', expect.objectContaining({ willAttemptReconnect: true })])
letTheMonitorReconnect()
expect(MockWebSocket.instances.length).toBeGreaterThan(1)
expect(consumer.connection.isOpen()).toBe(true)
expect(events).toContainEqual(['connected', { reconnected: true }])
// The subscription was re-established on the new socket
expect(MockWebSocket.last.commandsOfType('subscribe')).toEqual([
{ command: 'subscribe', identifier: channel.identifier },
])
})
it('retries a subscription the server never confirms', () => {
MockWebSocket.autoConfirmSubscriptions = false
const { channel } = subscribe()
expect(MockWebSocket.last.commandsOfType('subscribe')).toHaveLength(1)
jest.advanceTimersByTime(SubscriptionGuarantor.retryInterval * 3)
expect(MockWebSocket.last.commandsOfType('subscribe').length).toBeGreaterThan(1)
MockWebSocket.last.confirmSubscription(channel.identifier)
const afterConfirmation = MockWebSocket.last.commandsOfType('subscribe').length
jest.advanceTimersByTime(SubscriptionGuarantor.retryInterval * 5)
expect(MockWebSocket.last.commandsOfType('subscribe')).toHaveLength(afterConfirmation)
})
it('reports a rejected subscription and stops tracking it', () => {
MockWebSocket.autoConfirmSubscriptions = false
const { consumer, channel, events } = subscribe()
MockWebSocket.last.rejectSubscription(channel.identifier)
expect(events).toContainEqual(['rejected', undefined])
expect(consumer.subscriptions.subscriptions).toHaveLength(0)
expect(consumer.subscriptions.guarantor.pendingSubscriptions).toHaveLength(0)
})
it('stops reconnecting when the server disconnects for good', () => {
const { consumer, events } = subscribe()
MockWebSocket.last.deliver({ type: 'disconnect', reason: 'unauthorized', reconnect: false })
expect(events).toContainEqual(['disconnected', expect.objectContaining({ willAttemptReconnect: false })])
letTheMonitorReconnect()
expect(MockWebSocket.instances).toHaveLength(1)
expect(consumer.connection.isActive()).toBe(false)
})
it('surfaces socket errors to subscriptions', () => {
const { events } = subscribe()
const failure = new Error('network down')
MockWebSocket.last.fail(failure)
expect(events).toContainEqual(['error', { message: 'network down', event: failure }])
})
it('keeps working when the server broadcasts unusual payloads', () => {
const { channel, events } = subscribe()
expect(() => {
MockWebSocket.last.broadcast(channel.identifier, null)
MockWebSocket.last.broadcast(channel.identifier, 'a plain string')
MockWebSocket.last.broadcast(channel.identifier, [1, 2, 3])
MockWebSocket.last.deliverRaw(JSON.stringify({ identifier: channel.identifier }))
}).not.toThrow()
expect(events.filter(([name]) => name === 'received')).toEqual([
['received', { action: 'received' }],
['received', 'a plain string'],
['received', [1, 2, 3]],
['received', { action: 'received' }],
])
})
it('does not throw when sending while the connection is down', () => {
const { consumer, channel } = subscribe()
consumer.disconnect()
expect(() => channel.perform('speak', { text: 'nobody listening' })).not.toThrow()
expect(consumer.send({ command: 'message' })).toBe(false)
})
it('resubscribes every channel after a reconnect', () => {
const consumer = ActionCable.createConsumer('wss://example.com/cable')
const chat = consumer.subscriptions.create('ChatChannel')
const inbox = consumer.subscriptions.create('InboxChannel')
flushSocketWork()
MockWebSocket.last.drop()
letTheMonitorReconnect()
expect(MockWebSocket.last.commandsOfType('subscribe').map(c => c.identifier)).toEqual([
chat.identifier,
inbox.identifier,
])
})
})