import { QueryClientProvider } from '@tanstack/react-query' import { renderHook, waitFor } from '@testing-library/react-native' import React from 'react' import { buildTestQueryClient } from '../../__utils__/query_client' import { ChatContext, ChatContextValue } from '../../contexts/chat_context' import { useApiGet } from '../../hooks/use_api' import { ApiClient, useApiClient } from '../../hooks/use_api_client' import { Session } from '../../utils' import { ResponseError } from '../../utils/response_error' jest.mock('../../hooks/use_api_client') const mockedUseApiClient = useApiClient as jest.MockedFunction let get: jest.Mock const renderUseApiGet = (session: Session) => { const queryClient = buildTestQueryClient() const wrapper = ({ children }: { children: React.ReactNode }) => ( {children} ) return renderHook(() => useApiGet({ url: '/me', data: { fields: { Person: ['id'] } } }), { wrapper, }) } beforeEach(() => { get = jest.fn().mockResolvedValue({ data: { id: 1 } }) mockedUseApiClient.mockReturnValue({ chat: { get } } as unknown as ApiClient) }) afterEach(() => { jest.clearAllMocks() }) describe('useApiGet', () => { it('does not fetch while the session has no access token', () => { const { result } = renderUseApiGet(new Session()) expect(result.current.fetchStatus).toBe('idle') expect(get).not.toHaveBeenCalled() }) it('fetches once the session carries an access token', async () => { renderUseApiGet(new Session({ token: { access_token: 'a-real-token' } })) await waitFor(() => expect(get).toHaveBeenCalledTimes(1)) }) it('wraps HTTP errors in ResponseError', async () => { get.mockRejectedValue(new Response(null, { status: 429, statusText: 'Too Many Requests' })) const { result } = renderUseApiGet(new Session({ token: { access_token: 'a-real-token' } })) await waitFor(() => expect(result.current.isError).toBe(true)) expect(result.current.error).toBeInstanceOf(ResponseError) expect((result.current.error as ResponseError).status).toBe(429) }) })