'Apollo Mock Error state -> Error: No more mocked responses for the query

What am I trying to do?

Using MockProvider from @apollo/client/testing to mock out error state of a query.

What do I expect to get?

The component uses useLazyQuery to query something from backend, and returns an error, which will trigger the component to render the error message.

The component is working as expected.

What actually do I get?

Error: Uncaught [Error: No more mocked responses for the query ... And the test does not pass.

What have I tried?

  1. Final state is working as expected. I tried removing the error state in the mock data, everything worked as normal.
  2. I tried to wait longer, and it does not help
  3. I tried to log the error in the component, I could see the error. It looks like the MockProvider is missing something, and it errors out before even rendering the component
  4. I tried to remove the data portion, or added it back into the mock. See code below

Where are your codes?

Try #1

const mock = {
      request: { query: GET_REFERRER_FROM_CODE, variables: { input: "edx" } },
      result: {
        errors: [new GraphQLError("Error!")],
        data: {
          userGetReferrerFromCode: {
            id: "abc",
            firstName: "Leo",
            lastName: "Qiu",
          },
        },
      },
    };

Try #2

const mock = {
      request: { query: GET_REFERRER_FROM_CODE, variables: { input: "edx" } },
      result: {
        errors: [new GraphQLError("Error!")],
      },
    };

Basecode

<MockedProvider addTypename={false} mocks={mocks}>
   ...
</MockedProvider>


Solution 1:[1]

From experience, I've found that the error field does not need to be nested in the result to trigger an error.

e.g.

const mocks = [
    {
        request: { query: GET_REFERRER_FROM_CODE, variables: { input: "edx" } },      
        error: {
            message: "Something went wrong",
        },
    }
];

Then when using

const { loading, data, error } = useQuery(GET_REFERRER_FROM_CODE, {
    variables: { input: "edx" },
});

error will contain the object from the mock.

Solution 2:[2]

If your code does multiple requests (or refetch) you need to duplicate your mock x times.

So if you do query1, then refetch query1, you need to provide 2 exact same mocks eg [mock1, mock1]

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 peteredhead
Solution 2 YEVY