1
votes

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>
1
Did you find solution to this?Pritesh Acharya

1 Answers

0
votes

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.