-
Notifications
You must be signed in to change notification settings - Fork 11.4k
/
Copy pathuseGetMore.spec.ts
80 lines (67 loc) · 2.53 KB
/
useGetMore.spec.ts
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
import { renderHook } from '@testing-library/react';
import React from 'react';
import { useGetMore } from './useGetMore';
import { RoomHistoryManager } from '../../../../../app/ui-utils/client';
jest.mock('../../../../../app/ui-utils/client', () => ({
RoomHistoryManager: {
isLoading: jest.fn(),
hasMore: jest.fn(),
hasMoreNext: jest.fn(),
getMore: jest.fn(),
getMoreNext: jest.fn(),
},
}));
const mockGetMore = jest.fn();
describe('useGetMore', () => {
it('should call getMore when scrolling near top and hasMore is true', () => {
(RoomHistoryManager.isLoading as jest.Mock).mockReturnValue(false);
(RoomHistoryManager.hasMore as jest.Mock).mockReturnValue(true);
(RoomHistoryManager.hasMoreNext as jest.Mock).mockReturnValue(false);
(RoomHistoryManager.getMore as jest.Mock).mockImplementation(mockGetMore);
const atBottomRef = { current: false };
const mockElement = {
addEventListener: jest.fn((event, handler) => {
if (event === 'scroll') {
handler({
target: {
scrollTop: 10,
clientHeight: 300,
},
});
}
}),
removeEventListener: jest.fn(),
};
const useRefSpy = jest.spyOn(React, 'useRef').mockReturnValueOnce({ current: mockElement });
const { unmount } = renderHook(() => useGetMore('room-id', atBottomRef), { legacyRoot: true });
expect(useRefSpy).toHaveBeenCalledWith(null);
expect(RoomHistoryManager.getMore).toHaveBeenCalledWith('room-id');
unmount();
expect(mockElement.removeEventListener).toHaveBeenCalledWith('scroll', expect.any(Function));
});
it('should call getMoreNext when scrolling near bottom and hasMoreNext is true', () => {
(RoomHistoryManager.isLoading as jest.Mock).mockReturnValue(false);
(RoomHistoryManager.hasMore as jest.Mock).mockReturnValue(false);
(RoomHistoryManager.hasMoreNext as jest.Mock).mockReturnValue(true);
(RoomHistoryManager.getMoreNext as jest.Mock).mockImplementation(mockGetMore);
const atBottomRef = { current: false };
const mockElement = {
addEventListener: jest.fn((event, handler) => {
if (event === 'scroll') {
handler({
target: {
scrollTop: 600,
clientHeight: 300,
scrollHeight: 800,
},
});
}
}),
removeEventListener: jest.fn(),
};
const useRefSpy = jest.spyOn(React, 'useRef').mockReturnValueOnce({ current: mockElement });
renderHook(() => useGetMore('room-id', atBottomRef), { legacyRoot: true });
expect(useRefSpy).toHaveBeenCalledWith(null);
expect(RoomHistoryManager.getMoreNext).toHaveBeenCalledWith('room-id', atBottomRef);
});
});