reactjsjestjsreact-queryreact-custom-hooks

What should I do to pass this React custom hook test?


"I'm new to testing. I've been attempting to test my custom hook, but despite encountering numerous errors, I still haven't been able to pass the test. The hook simply utilizes the useQuery hook to return an API response, but it consistently returns 'undefined.' Any suggestions, please?"

export const retrieveData = async () => {
  const response = await axios.get('http://localhost:8080/jaime/')
  //   console.log(response)
  return response.data
}

// This is the hook I would like to test:
export function useJaime() {
  const {
    data: jaimeRamirez,
    error,
    isLoading,
  } = useQuery('DadosDoJaime', retrieveData)

  return { jaimeRamirez, error, isLoading }
}

This is the test so far:

const infoJaime = {
  nombre: 'Jaime Ramírez',
  compania: 'Microsoft',
  coche: 'Porsche',
}

const createWrapper = () => {
  const queryClient = new QueryClient()
  return ({ children }) => (
    <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
  )
}

describe('Testando hooks customizados: ', () => {
  test('useJaime', async () => {
    const { result } = renderHook(() => useJaime(), {
      wrapper: createWrapper(),
    })

    act(() => {
      expect(result.current.jaimeRamirez).toEqual(infoJaime)
    })
  })
})

And this is the result:

Any help would be highly appreciated, Thanks in advance

I've been trying to work with async functions, but no success at all.


Solution

  • First you need to mock your response data coming from axios

    import axios from 'axios';
    
    jest.mock('axios');
    axios.get = jest.fn().mockResolvedValue({ data: infoJaime });
    

    Then you can make some assertions like this

    expect(result.current.jaimeRamirez).toEqual(infoJaime)
    

    But make sure those are asynchronous

    Complete code

    jest.mock('axios');
    
    describe('Testando hooks customizados: ', () => {
      test('useJaime', async () => {
        axios.get = jest.fn().mockResolvedValue({ data: infoJaime });
    
        const { result } = renderHook(() => useJaime(), {
          wrapper: createWrapper(),
        });
    
        await waitFor(() => expect(result.current.jaimeRamirez).toEqual(infoJaime));
      });
    });