How to mock the useApolloClient hook?

491 Views Asked by At

Apollo Client provides this doc for testing APIs with MockedProvider, but it doesn't seem to mock the useApolloClient hook. When I use MockedProvider with my functional component and run the test, I get this error even though I've added MockedProvider while mounting:

Invariant Violation: No Apollo Client instance can be found. Please ensure that you have called `ApolloProvider` higher up in your tree.

      72 |   );
      73 |
    > 74 |   const makeCall = useApolloClient();

This is how I mounted it:

const mockResponses = [];
const wrapper = mount(
    <MockedProvider mocks={mockResponses} addTypename={false}>
      <Provider store={store}>
          <PriceComponent
            ...someProps
          />
      </Provider>
    </MockedProvider>
  );

Any ideas what might be going wrong?

1

There are 1 best solutions below

0
On

I'd recommend you create a wrapper for this so it can be re-used where needed.

import { MockedProvider, MockedResponse } from "@apollo/client/testing";
import { render, RenderResult } from "@testing-library/react";
import { FC, ReactElement } from "react";

function renderWithApolloProvider(
  ui: ReactElement,
  mocks: MockedResponse<Record<string, any>>[] = [],
): RenderResult {
  const Wrapper: FC = ({ children }) => {
      return (
          <MockedProvider mocks={mocks}>
              {children}
          </MockedProvider>
      );
  };

  return render(ui, { wrapper: Wrapper });
};

Then you can use it in your tests like this:

const mocks = [
  // Your GraphQL mocks
];

renderWithApolloProvider(
  <PriceComponent
     ...someProps
  />,
  mocks
);

I used the react testing library for the example above.

You seem to be using enzyme to test your components so try this

function mountWithApolloProvider(
    Component,
    mocks = [],
) {
  const wrapper = mount(
     <Provider store={store}>
       <MockedProvider mocks={mocks} addTypename={false}>
          <Component />
       </MockedProvider>
     </Provider>
  )
  return wrapper;
}

Usage:

const mocks = [
  // Your GraphQL mocks
];

renderWithApolloProvider(
  PriceComponent,
  mocks
);