'Testing function that use useQuery @apollo/client with Jest

I am trying to unit test my function that call useQuery from @apollo/client.

Here's what I have done

getPixelID.ts

import { useQuery } from '@apollo/client';
import { GET_PIXEL_ID } from '../query';

export const GetPixelID = (brandId:string) => {
  const { data } = useQuery(GET_PIXEL_ID, {
    variables: {
      input: {
        brandId: brandId,
      },
      fetchPolicy: 'network-only',
    },
    onCompleted: () => {
      console.log('Complete Fetching PixelID:', data);
    },
    onError: (error) => {
      console.error(`Error getting PixelID. ${error.message}`);
    },
  });

  return data?.facebookPixelId?.pixelId;
};

getPixelID.test.ts

import { GetPixelID } from '../helpers/getPixelID';
import { renderHook } from '@testing-library/react-hooks';
import { MockedProvider } from '@apollo/client/testing';


jest.mock('@apollo/react-hooks', () => {
  const data = {
    facebookPixelId: {
      pixelId: '123',
    },
  };

  return {
    __esModule: true,
    useQuery: jest.fn(() => ({ data })),
  };
});

describe('Test GetPixelID', () => {
  it('Successfully fetching PixelID', () => {
    const { result } = renderHook(() => GetPixelID('123'), {
      wrapper: MockedProvider
    });

    expect(result.current).toBeTruthy();
  });
});

But it always show this

enter image description here

As far as I know, useQuery need to be wrapped inside ApolloClient (in this case is MockedProvider), but I don't why it doesn't run. Trying to remove the wrapper will show another error that "no Apollo Client is found", Any help?



Solution 1:[1]

I'm a bit late to the party but the issue probably occurs because you're mocking the wrong hook. In your component you import useQuery from @apollo/client.

import { useQuery } from '@apollo/client'

But in your test, you're trying to mock useQuery from @apollo/react-hook.

jest.mock('@apollo/react-hooks', () => {...}

Simply changing this to jest.mock('@apollo/client', () => {...} should fix it.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 root