BlogEx
BACK TO FEED
2022.08.28 ● PUBLIC

Infinite loop in useEffect when mocking GraphQL API

reactjestgraphql

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];
},
};
});