|
| 1 | +import type { ILivechatTag, Serialized } from '@rocket.chat/core-typings'; |
| 2 | +import { MockedAppRootBuilder } from '@rocket.chat/mock-providers/dist/MockedAppRootBuilder'; |
| 3 | +import { act, renderHook, waitFor } from '@testing-library/react'; |
| 4 | + |
| 5 | +import type { TagListItem } from './useTagsList'; |
| 6 | +import { useTagsList } from './useTagsList'; |
| 7 | +import { createFakeTag } from '../../../../tests/mocks/data'; |
| 8 | + |
| 9 | +const formatTagItem = (tag: Serialized<ILivechatTag>): TagListItem => ({ |
| 10 | + _id: tag._id, |
| 11 | + label: tag.name, |
| 12 | + value: tag.name, |
| 13 | +}); |
| 14 | + |
| 15 | +const mockGetTags = jest.fn(); |
| 16 | + |
| 17 | +const appRoot = new MockedAppRootBuilder().withEndpoint('GET', '/v1/livechat/tags', mockGetTags); |
| 18 | + |
| 19 | +afterEach(() => { |
| 20 | + jest.clearAllMocks(); |
| 21 | +}); |
| 22 | + |
| 23 | +it('should fetch tags', async () => { |
| 24 | + const limit = 5; |
| 25 | + |
| 26 | + const data = Array.from({ length: 10 }, () => createFakeTag()); |
| 27 | + |
| 28 | + mockGetTags.mockImplementation(({ offset, count }: { offset: number; count: number }) => { |
| 29 | + const tags = data.slice(offset, offset + count); |
| 30 | + |
| 31 | + return { |
| 32 | + tags, |
| 33 | + count, |
| 34 | + offset, |
| 35 | + total: data.length, |
| 36 | + }; |
| 37 | + }); |
| 38 | + |
| 39 | + const { result } = renderHook(() => useTagsList({ filter: '', limit }), { wrapper: appRoot.build() }); |
| 40 | + |
| 41 | + expect(result.current.isFetching).toBe(true); |
| 42 | + await waitFor(() => expect(result.current.isFetching).toBe(false)); |
| 43 | + |
| 44 | + expect(mockGetTags).toHaveBeenCalled(); |
| 45 | + expect(result.current.data).toEqual(data.slice(0, 5).map(formatTagItem)); |
| 46 | + |
| 47 | + await act(() => result.current.fetchNextPage()); |
| 48 | + |
| 49 | + expect(mockGetTags).toHaveBeenCalledTimes(2); |
| 50 | + await waitFor(() => expect(result.current.data).toHaveLength(10)); |
| 51 | + expect(result.current.data).toEqual(data.map(formatTagItem)); |
| 52 | + |
| 53 | + await act(() => result.current.fetchNextPage()); |
| 54 | + |
| 55 | + // should not fetch again since total was reached |
| 56 | + expect(mockGetTags).toHaveBeenCalledTimes(2); |
| 57 | +}); |
0 commit comments