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