Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mocking React Query Hook in Vitest

My component:

export const Product = () => {
  const navigate = useNavigate()
  const { id } = useParams()
  const { data } = useFetchQueries()
  return (
    <Modal>
      <Box>
        {data.data
          .filter((elem: TableElemType) => elem.id.toString() === id)
          .map((elem: TableElemType) => {
            return <ProductData data={elem} key={elem.id} />
          })}
      </Box>
    </Modal>
  )
}

UseFetchQueries:

export const useFetchQueries = () => {
  const fetcher = async () => {
    const res = await fetch(`https://reqres.in/api/products`)
      .then((res) => res.json())
      .then((data) => {
        return data
      })
      .catch((err) => {
        return err.message
      })
    console.log(res)
    return res
  }
  return useQuery(['products'], async () => fetcher())
}

I want to test it and mock recieved data from useFetchQueries in Vitest. How to do it?

I did something like this, but I don't know how to implement this mock to my component.

vi.mock('./useFetchQueries', () => ({
    useFetchQueries: vi.fn().mockReturnValue({ data: { data: ['string'] } }),
}))

describe('ProducData', () => {
    it('if renders proper data', async () => {
        render(renderWithRouter(<Product />, '/5'))
        expect(useFetchQueries).toHaveBeenCalled()
    })
})
like image 311
strB Avatar asked Oct 21 '25 04:10

strB


1 Answers

The recommended approach is to not mock the result of the hook, but mock the network response:

  • https://tanstack.com/query/v4/docs/react/guides/testing#testing-network-calls
  • https://tkdodo.eu/blog/testing-react-query
like image 115
TkDodo Avatar answered Oct 22 '25 21:10

TkDodo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!