Merge branch 'feat/inda-383-daily-stat' into 'main'
[ProtonMail-WebClient.git] / packages / docs-core / lib / Realtime / WebsocketState.spec.ts
blob77f3f8695d2519cd34bf73dfcfe1c8078b4b07ad
1 import { WebsocketState } from './WebsocketState'
3 describe('WebsocketState', () => {
4   let state: WebsocketState
6   beforeEach(() => {
7     state = new WebsocketState()
8   })
10   afterEach(() => {
11     state.destroy()
12   })
14   describe('attempt count', () => {
15     it('should increment attempts on close', () => {
16       state.didClose()
18       expect(state.attemptCount).toBe(1)
20       state.didClose()
22       expect(state.attemptCount).toBe(2)
23     })
25     it('should increment attempts on fail to fetch token', () => {
26       state.didFailToFetchToken()
28       expect(state.attemptCount).toBe(1)
30       state.didFailToFetchToken()
32       expect(state.attemptCount).toBe(2)
33     })
34   })
36   describe('connection', () => {
37     it('should not be connected initially', () => {
38       expect(state.isConnected).toBe(false)
39     })
41     it('should set connected on open', () => {
42       state.didOpen()
44       expect(state.isConnected).toBe(true)
45     })
46   })
48   describe('exponential backoff', () => {
49     it('should have minimum 2 second backoff if no attempts', () => {
50       expect(state.getBackoffWithoutJitter()).toBe(2000)
51     })
53     it('should return backoff time and limit to max backoff time', () => {
54       state.didClose()
55       expect(state.getBackoffWithoutJitter()).toBe(2000)
57       state.didClose()
58       expect(state.getBackoffWithoutJitter()).toBe(4000)
60       state.didClose()
61       expect(state.getBackoffWithoutJitter()).toBe(8000)
63       state.didClose()
64       expect(state.getBackoffWithoutJitter()).toBe(16000)
66       state.didClose()
67       expect(state.getBackoffWithoutJitter()).toBe(32000)
69       state.didClose()
70       expect(state.getBackoffWithoutJitter()).toBe(32000)
71     })
73     it('should reset attempts', () => {
74       state.didClose()
75       expect(state.getBackoffWithoutJitter()).toBe(2000)
77       state.didClose()
78       expect(state.getBackoffWithoutJitter()).toBe(4000)
80       state.resetAttempts()
81       expect(state.getBackoffWithoutJitter()).toBe(2000)
82     })
84     it('should get backoff with jitter', () => {
85       state.getJitterFactor = jest.fn().mockReturnValue(1)
87       state.didClose()
88       expect(state.getBackoff()).toBe(2000)
90       state.getJitterFactor = jest.fn().mockReturnValue(1.5)
92       state.didClose()
93       expect(state.getBackoff()).toBe(6000)
94     })
95   })