-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathspotifyPolling.test.ts
More file actions
451 lines (390 loc) · 15.6 KB
/
Copy pathspotifyPolling.test.ts
File metadata and controls
451 lines (390 loc) · 15.6 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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
/**
* Unit tests for Spotify integration with timer
* Tests Spotify commands and volume control
*/
import { beforeEach, describe, expect, it, jest } from '@jest/globals'
import { SpotifyPolling } from '../../services/spotifyPolling'
import { SpotifyTokenManager } from '../../services/spotifyTokenManager'
import { SpotifyData } from '../../types/websocket'
import logger from '../../utils/logger'
// Mock the logger
jest.mock('../../utils/logger', () => ({
debug: jest.fn(),
info: jest.fn(),
warn: jest.fn(),
error: jest.fn(),
}))
// Mock the SpotifyTokenManager module
jest.mock('../../services/spotifyTokenManager', () => {
const SpotifyTokenManager = jest.fn().mockImplementation(() => {
return {
getValidAccessToken: jest
.fn()
.mockImplementation(() => Promise.resolve('mock_access_token')),
getSdkAccessToken: jest.fn().mockReturnValue({
access_token: 'mock_access_token',
token_type: 'Bearer',
expires_in: 3600,
}),
}
})
return {
SpotifyTokenManager,
}
})
const mockPlayer: { [key: string]: jest.Mock } = {
getCurrentlyPlayingTrack: jest
.fn()
.mockImplementation(() => Promise.resolve(null)),
startResumePlayback: jest.fn().mockImplementation(() => Promise.resolve()),
pausePlayback: jest.fn().mockImplementation(() => Promise.resolve()),
skipToNext: jest.fn().mockImplementation(() => Promise.resolve()),
skipToPrevious: jest.fn().mockImplementation(() => Promise.resolve()),
transferPlayback: jest.fn().mockImplementation(() => Promise.resolve()),
setPlaybackVolume: jest.fn().mockImplementation(() => Promise.resolve()),
getAvailableDevices: jest
.fn()
.mockImplementation(() => Promise.resolve({ devices: [] })),
}
jest.mock('@spotify/web-api-ts-sdk', () => ({
SpotifyApi: {
withAccessToken: jest.fn(() => ({
player: mockPlayer,
})),
},
AccessToken: jest.fn(),
}))
import { ServerMessage } from '../../types/websocket'
describe('SpotifyPolling Service', () => {
let spotifyService: SpotifyPolling
let broadcastMock: jest.Mock<(message: ServerMessage) => void>
let broadcastedStates: SpotifyData[]
beforeEach(async () => {
jest.useFakeTimers()
jest.clearAllMocks()
// Reset mockPlayer's mocks
mockPlayer.getCurrentlyPlayingTrack.mockClear()
mockPlayer.startResumePlayback.mockClear()
mockPlayer.pausePlayback.mockClear()
mockPlayer.skipToNext.mockClear()
mockPlayer.skipToPrevious.mockClear()
mockPlayer.transferPlayback.mockClear()
mockPlayer.setPlaybackVolume.mockClear()
mockPlayer.getAvailableDevices.mockClear()
mockPlayer.getAvailableDevices.mockResolvedValue({ devices: [] })
broadcastedStates = []
broadcastMock = jest.fn((message) => {
if (message.type === 'SPOTIFY_UPDATE') {
broadcastedStates.push(message.payload)
}
})
// Mock environment variables
process.env.SPOTIFY_CLIENT_ID = 'test_client_id'
process.env.SPOTIFY_CLIENT_SECRET = 'test_client_secret'
process.env.SPOTIFY_DEBUG = 'false' // Disable debug logging in tests
// Initialize the service and await its creation, which includes SDK setup
spotifyService = await SpotifyPolling.create(broadcastMock)
// Stop polling after service creation to avoid side effects in tests
if ((spotifyService as unknown)['pollInterval']) {
clearInterval(
(spotifyService as unknown)['pollInterval'] as NodeJS.Timeout
)
;(spotifyService as unknown)['pollInterval'] = null
}
if ((spotifyService as unknown)['tokenRefreshInterval']) {
clearInterval(
(spotifyService as unknown)['tokenRefreshInterval'] as NodeJS.Timeout
)
;(spotifyService as unknown)['tokenRefreshInterval'] = null
}
})
afterEach(() => {
// Ensure polling is stopped and all timers are cleared
if (spotifyService) {
spotifyService.stopPolling()
spotifyService.cleanup()
}
jest.clearAllTimers()
jest.useRealTimers()
})
describe('Initialization', () => {
it('should initialize with default state', () => {
const state = spotifyService.getState()
expect(state.trackName).toBe('Awaiting Login...')
expect(state.artist).toBe('')
expect(state.isPlaying).toBe(false)
})
})
describe('Command Handling', () => {
it('should handle PLAY command', async () => {
await spotifyService.handleCommand('PLAY', 'test_device_id') // Assuming a deviceId is passed
expect(mockPlayer.startResumePlayback).toHaveBeenCalledWith(
'test_device_id'
)
})
it('should handle PAUSE command', async () => {
await spotifyService.handleCommand('PAUSE', 'test_device_id')
expect(mockPlayer.pausePlayback).toHaveBeenCalledWith('test_device_id')
})
it('should handle NEXT command', async () => {
await spotifyService.handleCommand('NEXT', 'test_device_id')
expect(mockPlayer.skipToNext).toHaveBeenCalledWith('test_device_id')
})
it('should handle PREVIOUS command', async () => {
await spotifyService.handleCommand('PREVIOUS', 'test_device_id')
expect(mockPlayer.skipToPrevious).toHaveBeenCalledWith('test_device_id')
})
it('should include device ID when provided', async () => {
const deviceId = 'test_device_123'
await spotifyService.handleCommand('PLAY', deviceId)
expect(mockPlayer.startResumePlayback).toHaveBeenCalledWith(deviceId)
})
})
describe('Volume Control', () => {
it('should set volume with SET_VOLUME command', async () => {
await spotifyService.handleCommand('SET_VOLUME', undefined, 75)
expect(mockPlayer.setPlaybackVolume).toHaveBeenCalledWith(75, undefined)
})
it('should clamp volume to 0-100 range', async () => {
await spotifyService.handleCommand('SET_VOLUME', undefined, 150)
expect(mockPlayer.setPlaybackVolume).toHaveBeenCalledWith(100, undefined)
})
it('should clamp negative volume to 0', async () => {
await spotifyService.handleCommand('SET_VOLUME', undefined, -10)
expect(mockPlayer.setPlaybackVolume).toHaveBeenCalledWith(0, undefined)
})
it('should round volume to nearest integer', async () => {
await spotifyService.handleCommand('SET_VOLUME', undefined, 75.7)
expect(mockPlayer.setPlaybackVolume).toHaveBeenCalledWith(76, undefined)
})
it('should return true on successful volume change', async () => {
mockPlayer.setPlaybackVolume.mockImplementation(() => Promise.resolve())
await spotifyService.handleCommand('SET_VOLUME', undefined, 50)
expect(mockPlayer.setPlaybackVolume).toHaveBeenCalledWith(50, undefined)
})
it('should return false on failed volume change', async () => {
mockPlayer.setPlaybackVolume.mockImplementation(() =>
Promise.reject(new Error('API Error'))
)
await spotifyService.handleCommand('SET_VOLUME', undefined, 50)
expect(mockPlayer.setPlaybackVolume).toHaveBeenCalledWith(50, undefined)
})
})
describe('Device Management', () => {
it('should get available devices', async () => {
const mockDevices = [
{
id: 'device1',
name: 'Speaker',
type: 'Speaker',
is_active: true,
is_private_session: false,
is_restricted: false,
volume_percent: 50,
},
{
id: 'device2',
name: 'Phone',
type: 'Smartphone',
is_active: false,
is_private_session: false,
is_restricted: false,
volume_percent: 30,
},
]
mockPlayer.getAvailableDevices.mockImplementation(() =>
Promise.resolve({
devices: mockDevices,
})
)
const devices = await spotifyService.getAvailableDevices()
expect(devices).toHaveLength(2)
expect(devices[0].id).toBe('device1')
expect(devices[1].id).toBe('device2')
})
it('should transfer playback to device', async () => {
const deviceId = 'device123'
await spotifyService.handleCommand('TRANSFER_PLAYBACK', deviceId)
expect(mockPlayer.transferPlayback).toHaveBeenCalledWith([deviceId], true)
})
it('should handle TRANSFER_PLAYBACK command', async () => {
const deviceId = 'device123'
await spotifyService.handleCommand('TRANSFER_PLAYBACK', deviceId)
expect(mockPlayer.transferPlayback).toHaveBeenCalledWith([deviceId], true)
})
})
describe('Token Management', () => {
it('should accept refresh token', async () => {
const refreshToken = 'test_refresh_token'
// Mock the initializeSdk to resolve immediately
const initializeSdkSpy = jest
.spyOn(spotifyService as never, 'initializeSdk')
.mockResolvedValue(undefined)
spotifyService.setRefreshToken(refreshToken)
// Advance timers to allow setTimeout to run
jest.advanceTimersByTime(1000)
expect(initializeSdkSpy).toHaveBeenCalled()
initializeSdkSpy.mockRestore()
})
it('should not execute commands without access token', async () => {
// Override the mock to return null token for this test to ensure SDK is not initialized
;(SpotifyTokenManager as unknown as jest.Mock).mockImplementationOnce(
() => ({
getValidAccessToken: jest.fn().mockResolvedValue(null),
getSdkAccessToken: jest.fn().mockReturnValue(null),
})
)
const newService = await SpotifyPolling.create(broadcastMock)
await newService.handleCommand('PLAY')
// Should not make API call without token
expect(mockPlayer.startResumePlayback).not.toHaveBeenCalled()
})
})
describe('Playback State', () => {
it('should broadcast state when track changes', async () => {
const mockPlayback = {
item: {
id: 'track123',
name: 'Test Track',
artists: [{ name: 'Test Artist' }],
type: 'track',
},
is_playing: true,
currently_playing_type: 'track',
}
mockPlayer.getCurrentlyPlayingTrack.mockImplementation(() =>
Promise.resolve(mockPlayback)
)
spotifyService.startPolling(100)
jest.advanceTimersByTime(150)
await Promise.resolve()
await Promise.resolve()
spotifyService.stopPolling()
// Only check the last broadcasted state
const lastState = broadcastedStates.at(-1)
expect(lastState?.trackName).toBe('Test Track')
})
it('should handle 204 No Content response', async () => {
mockPlayer.getCurrentlyPlayingTrack.mockImplementation(() =>
Promise.resolve(null)
)
spotifyService.startPolling(100)
jest.advanceTimersByTime(150)
await Promise.resolve()
await Promise.resolve()
spotifyService.stopPolling()
// Only check the last broadcasted state
const lastState = broadcastedStates.at(-1)
expect(lastState?.trackName).toBe('Nothing is currently playing.')
})
})
describe('Integration with Timer', () => {
it('should support NEXT command when timer starts', async () => {
// Simulate timer start triggering NEXT
await spotifyService.handleCommand('NEXT', 'test_device_id')
expect(mockPlayer.skipToNext).toHaveBeenCalledWith('test_device_id')
})
it('should support PAUSE command when timer stops', async () => {
// Simulate timer stop triggering PAUSE
await spotifyService.handleCommand('PAUSE', 'test_device_id')
expect(mockPlayer.pausePlayback).toHaveBeenCalledWith('test_device_id')
})
it('should handle rapid command sequences', async () => {
jest.clearAllMocks()
// Simulate rapid commands that might happen during workout
await spotifyService.handleCommand('PLAY', 'test_device_id')
await spotifyService.handleCommand('NEXT', 'test_device_id')
await spotifyService.handleCommand('PAUSE', 'test_device_id')
// Should have made 3 calls to the player methods
expect(mockPlayer.startResumePlayback).toHaveBeenCalledTimes(1)
expect(mockPlayer.skipToNext).toHaveBeenCalledTimes(1)
expect(mockPlayer.pausePlayback).toHaveBeenCalledTimes(1)
})
})
describe('Error Handling', () => {
it('should handle API errors gracefully', async () => {
mockPlayer.startResumePlayback.mockImplementation(() =>
Promise.reject(new Error('Network error'))
)
// Should not throw
await expect(
spotifyService.handleCommand('PLAY', 'test_device_id')
).resolves.not.toThrow()
expect(mockPlayer.startResumePlayback).toHaveBeenCalled()
})
it('should handle 401 unauthorized responses', async () => {
mockPlayer.getCurrentlyPlayingTrack.mockImplementation(() =>
Promise.reject({ status: 401 })
)
spotifyService.startPolling(100)
jest.advanceTimersByTime(150)
await Promise.resolve() // Flush promises
await Promise.resolve() // Flush promises
spotifyService.stopPolling()
// Should attempt to handle 401 without crashing
expect(() => spotifyService.getState()).not.toThrow()
})
it('should not execute commands without access token', async () => {
// Mock SpotifyPolling.create to return an instance with a null SDK
const originalSpotifyPollingCreate = SpotifyPolling.create
SpotifyPolling.create = jest.fn().mockResolvedValue({
handleCommand: jest.fn(() => Promise.resolve()), // Mock handleCommand to return a resolved promise
getState: jest.fn(),
stopPolling: jest.fn(),
cleanup: jest.fn(),
initializeSdk: jest.fn(),
setRefreshToken: jest.fn(),
startPolling: jest.fn(),
getAvailableDevices: jest.fn(),
sdk: null, // Ensure SDK is null
})
const newService = await SpotifyPolling.create(broadcastMock)
await newService.handleCommand('SET_VOLUME', undefined, 50)
expect(mockPlayer.setPlaybackVolume).not.toHaveBeenCalled()
// Restore original SpotifyPolling.create
SpotifyPolling.create = originalSpotifyPollingCreate
})
it('should handle SyntaxError during error logging gracefully', async () => {
// Simulate an error that returns invalid JSON when text() is called
const errorResponse = {
response: {
text: jest.fn().mockResolvedValue('Invalid JSON'),
},
}
mockPlayer.startResumePlayback.mockRejectedValue(errorResponse)
await spotifyService.handleCommand('PLAY', 'device_id')
expect(logger.error).toHaveBeenCalledWith(
{ response: 'Invalid JSON' },
expect.stringContaining('Error executing Spotify command PLAY: Response body:')
)
})
it('should handle unexpected errors in error logging safely', async () => {
// Simulate a deeply nested error that might crash text() retrieval
const badError = {
response: {
text: jest.fn().mockRejectedValue(new Error('Stream closed'))
}
}
mockPlayer.startResumePlayback.mockRejectedValue(badError)
await spotifyService.handleCommand('PLAY', 'device_id')
expect(logger.error).toHaveBeenCalledWith(
{ err: expect.any(Error) },
expect.stringContaining(
'Error executing Spotify command PLAY: Failed to retrieve error response text:'
)
)
})
it('should handle direct SyntaxError gracefully (suppress logs)', async () => {
mockPlayer.startResumePlayback.mockRejectedValue(
new SyntaxError('Unexpected token')
)
await spotifyService.handleCommand('PLAY', 'device_id')
expect(logger.warn).toHaveBeenCalledWith(
expect.stringContaining(
'[SpotifyPolling] Command PLAY executed, but response was not valid JSON'
)
)
expect(logger.error).not.toHaveBeenCalled()
})
})
})