Skip to content

Infinite loop in useEffect when mocking GraphQL API

Published: at 09:23 AM

Symptoms

The code example below caused infinite loop in useEffect hook when testing with Jest.

jest.mock("libs/api/graphql", () => {
  return {
    ...jest.requireActual("libs/api/graphql"),
    useRelatedItemsLazyQuery: () => {
      return [jest.fn(), { data: { relatedItems: [] } }];
    },
  };
});

Fix

This is because the data returned from the mocked function is a new object every time, and useEffect cannot compare it to the previous value. The solution that worked for me is to move the response (2nd argument) to a separate variable, and return it every time.

jest.mock("libs/api/graphql", () => {
  const response = { data: { relatedItems: [] } };
  return {
    ...jest.requireActual("libs/api/graphql"),
    useRelatedItemsLazyQuery: () => {
      return [jest.fn(), response];
    },
  };
});