Mike-Gibson / mock-apollo-client

Helps unit test components which use the Apollo Client.
MIT License
117 stars 15 forks source link

How to handle the error states? #41

Closed sschneider-ihre-pvs closed 3 years ago

sschneider-ihre-pvs commented 3 years ago

I am trying to test the error states of the mocked client but I seem to be unable to catch or expect. How would I catch errors either from throws within the client or network ?

Mike-Gibson commented 3 years ago

Hi,

Have you come across Error States in the README?

After that, the error should be available to whatever is using the result of the query.

Are you able to share the code you are using in your test, and where you're trying to test when the query errors? Maybe I can help more with some code.

sschneider-ihre-pvs commented 3 years ago

I guess I found the problem but I will share the code anyway So trying to being smart I did this :)

const successQueryHandler: any = jest
  .fn()
  .mockReturnValue(Promise.resolve());

const errorQueryHandler: any = jest
   .fn()
   .mockReturnValue(Promise.reject(new Error('GraphQL Network Error'))
);

which then immediatly fired the error instead, this seems to work

const successQueryHandler: any = jest
  .fn()
  .mockReturnValue(Promise.resolve());

const errorQueryHandler: any = jest.fn(() =>
  Promise.reject(new Error('GraphQL Network Error'))
);
Mike-Gibson commented 3 years ago

Glad you resolved the problem!

Please feel free to ask any other questions you have while using the library. Always happy to help, and it's useful in case anything in the API or README can be improved.

As an aside, I tend to use mockResolvedValue and mockRejectedValue, the latter of which is equivalent to what you changed your error handler to be.