import { renderHook, waitFor } from '@testing-library/react'; import { mockSource, mockPlugin } from '../__mocks__/MockModels'; import { useSources, UseSourcesProps } from './useSources'; describe('useSources', () => { it('Should trigger, load the sources and attach plugin reference to source', async () => { const sources = [mockSource()]; const plugins = [mockPlugin()]; const onRequestSources = jest.fn().mockResolvedValue(sources); const { result } = renderHook(() => useSources({ onRequestSources, plugins })); expect(result.current.isLoading).toBe(true); expect(result.current.error).toBe(null); expect(result.current.data).toEqual([]); await waitFor(() => expect(result.current.isLoading).toBe(false)); expect(result.current.isLoading).toBe(false); expect(result.current.data).toEqual( sources.map((source) => { return { ...source, plugin: plugins[0] }; }), ); }); it('Should filters sources that plugins dont exist for', async () => { const sources = [mockSource({ type: 'dam' }), mockSource({ id: '2', type: 'matrix' })]; const plugins = [mockPlugin({ type: 'dam' })]; const onRequestSources = jest.fn().mockResolvedValue(sources); const { result } = renderHook(() => useSources({ onRequestSources, plugins })); expect(result.current.isLoading).toBe(true); expect(result.current.error).toBe(null); expect(result.current.data).toEqual([]); await waitFor(() => expect(result.current.isLoading).toBe(false)); expect(result.current.isLoading).toBe(false); expect(result.current.data).toEqual([{ ...sources[0], plugin: plugins[0] }]); expect(result.current.data.length).toEqual(1); }); it('Should calculate the async key from the plugins type so it wont always change on re-renders', async () => { const sources = [mockSource()]; const plugins = [mockPlugin()]; const onRequestSources = jest.fn().mockResolvedValue(sources); const { rerender, result } = renderHook((props: UseSourcesProps) => useSources({ onRequestSources: props?.onRequestSources || onRequestSources, plugins: props?.plugins || plugins }), ); expect(result.current.isLoading).toBe(true); expect(result.current.error).toBe(null); expect(result.current.data).toEqual([]); await waitFor(() => expect(result.current.isLoading).toBe(false)); expect(result.current.isLoading).toBe(false); expect(result.current.data).toEqual([{ ...sources[0], plugin: plugins[0] }]); // Wont go back to loading data (plugin keys havent changed) rerender({ onRequestSources, plugins: [mockPlugin()] }); expect(result.current.isLoading).toBe(false); // Will go back to loading as change in keys rerender({ onRequestSources, plugins: [mockPlugin(), mockPlugin({ type: 'matrix' })] }); expect(result.current.isLoading).toBe(true); // Will go back to loading as change in keys (order change will cause reload) rerender({ onRequestSources, plugins: [mockPlugin({ type: 'matrix' }), mockPlugin()] }); expect(result.current.isLoading).toBe(true); }); });