|
| 1 | +import { GroupChannel } from '@sendbird/chat/groupChannel'; |
| 2 | +import { renderHook, act } from '@testing-library/react'; |
| 3 | +import useReconnectOnIdle from '../useReconnectOnIdle'; |
| 4 | + |
| 5 | +describe('useReconnectOnIdle', () => { |
| 6 | + beforeAll(() => { |
| 7 | + // Mock dispatchEvent for the document object |
| 8 | + document.dispatchEvent = jest.fn(); |
| 9 | + jest.spyOn(document, 'addEventListener'); |
| 10 | + jest.spyOn(document, 'removeEventListener'); |
| 11 | + }); |
| 12 | + |
| 13 | + afterEach(() => { |
| 14 | + jest.clearAllMocks(); |
| 15 | + }); |
| 16 | + |
| 17 | + it('should update shouldReconnect on tab visibility change', () => { |
| 18 | + const hook = renderHook(() => useReconnectOnIdle(true, { url: 'url' } as GroupChannel, true)); |
| 19 | + expect(hook.result.current.shouldReconnect).toBe(false); |
| 20 | + |
| 21 | + act(() => { |
| 22 | + Object.defineProperty(document, 'hidden', { value: false, configurable: true }); |
| 23 | + document.dispatchEvent(new Event('visibilitychange')); |
| 24 | + }); |
| 25 | + expect(hook.result.current.shouldReconnect).toBe(false); |
| 26 | + }); |
| 27 | + |
| 28 | + it('should not update shouldReconnect on isOnline change', () => { |
| 29 | + const { result, rerender } = renderHook(({ isOnline }) => useReconnectOnIdle(isOnline, { url: 'url' } as GroupChannel, true), { |
| 30 | + initialProps: { isOnline: false }, |
| 31 | + }); |
| 32 | + expect(result.current.shouldReconnect).toBe(true); |
| 33 | + |
| 34 | + rerender({ isOnline: true }); |
| 35 | + expect(result.current.shouldReconnect).toBe(false); |
| 36 | + }); |
| 37 | + |
| 38 | + it('should not update shouldReconnect if reconnectOnIdle is false', async () => { |
| 39 | + const reconnectOnIdle = false; |
| 40 | + renderHook(({ isOnline }) => useReconnectOnIdle(isOnline, { url: 'url' } as GroupChannel, reconnectOnIdle), { |
| 41 | + initialProps: { isOnline: false }, |
| 42 | + }); |
| 43 | + |
| 44 | + const spy = jest.spyOn(document, 'addEventListener'); |
| 45 | + document.dispatchEvent(new Event('visibilitychange')); |
| 46 | + |
| 47 | + const lastCall = spy.mock.calls[spy.mock.calls.length - 1]; |
| 48 | + expect(lastCall).toEqual(['visibilitychange', expect.any(Function)]); |
| 49 | + spy.mockRestore(); |
| 50 | + }); |
| 51 | +}); |
0 commit comments