|
| 1 | +import React from 'react' |
| 2 | +import { renderHook } from 'react-hooks-testing-library' |
| 3 | +import mockedResponse from '../__mocks__/mocked-response.json' |
| 4 | +import { createFetchConnector, FetchConnector } from '../fetch-connector' |
| 5 | +import fetchJSON from '../fetch-json' |
| 6 | +import FetchConnectorContext from '../FetchConnectorContext' |
| 7 | +import useTriggerableFetch from '../use-triggerable-fetch' |
| 8 | + |
| 9 | +jest.mock('../internal/actHack') |
| 10 | +jest.mock('../fetch-json') |
| 11 | + |
| 12 | +const mockedFetchJSON = (fetchJSON as unknown) as jest.Mock<typeof fetchJSON> |
| 13 | + |
| 14 | +const createWrapperComponent = (connector: FetchConnector) => { |
| 15 | + const WrapperComponent: React.FC<{ children?: React.ReactNode }> = ({ |
| 16 | + children, |
| 17 | + }) => ( |
| 18 | + <FetchConnectorContext.Provider value={connector}> |
| 19 | + {children} |
| 20 | + </FetchConnectorContext.Provider> |
| 21 | + ) |
| 22 | + |
| 23 | + return WrapperComponent |
| 24 | +} |
| 25 | + |
| 26 | +describe('UseTriggerableFetchHook', () => { |
| 27 | + test('should fetch without error', async () => { |
| 28 | + const connector = createFetchConnector() |
| 29 | + const hook = renderHook(() => useTriggerableFetch('/foo'), { |
| 30 | + wrapper: createWrapperComponent(connector), |
| 31 | + }) |
| 32 | + |
| 33 | + expect(hook.result.current.error).toEqual(undefined) |
| 34 | + expect(hook.result.current.data).toEqual(undefined) |
| 35 | + expect(typeof hook.result.current.trigger).toEqual('function') |
| 36 | + expect(hook.result.current.loading).toEqual(false) |
| 37 | + hook.result.current.trigger() |
| 38 | + expect(hook.result.current.error).toEqual(undefined) |
| 39 | + expect(hook.result.current.data).toEqual(undefined) |
| 40 | + expect(typeof hook.result.current.trigger).toEqual('function') |
| 41 | + expect(hook.result.current.loading).toEqual(true) |
| 42 | + await hook.waitForNextUpdate() |
| 43 | + expect(hook.result.current.error).toEqual(undefined) |
| 44 | + expect(hook.result.current.data).toEqual(mockedResponse['/foo']) |
| 45 | + expect(typeof hook.result.current.trigger).toEqual('function') |
| 46 | + expect(hook.result.current.loading).toEqual(false) |
| 47 | + expect(mockedFetchJSON.mock.calls.length).toBe(1) |
| 48 | + }) |
| 49 | +}) |
0 commit comments