Mock All GraphQL Operations in MSW

Share this video with your friends

Send Tweet

Let's improve our schema-first GraphQL mocks by intercepting all GraphQL operations—both queries and mutations—using a single Mock Service Worker graphql.operation() request handler.

~ 2 months ago

Is there a way to type annotate the returned data? I get the following error from ts

Type 'ObjMap<unknown> | null | undefined' is not assignable to type 'null | undefined'.
  Type 'ObjMap<unknown>' is not assignable to type 'null | undefined'.

Shouldn't data be something like Review | Array<Review> and expand from there as we add to executeGraphQL? Also I'm having a hard time following the client side code to see where it is expecting null | undefined

Thanks

~ 2 months ago

I meant to say I have defined the type Review based on type Review in the schema and I'm referring to the data returned by executeGraphQL.

When I return it as return HttpResponse.json({ errors, data }); this is where I get the error because the expected response is just null | undefined

Artem Zakharchenko
Artem Zakharchenko(instructor)
~ 2 months ago

Hi! Please, do you have a reproduction repo I can look at? It's quite difficult to suggest anything by text alone. I'm sure we can figure this one out quickly and have your mocked response type-safe. Thanks.

~ 2 months ago

Yes sir. msw-course

~ 2 months ago

It occurred to me that this project for the course is for demo purposes of MSW and all of that is working so no problem there. My TS problem I think is in the useQuery hook where I'm a bit lost on the code. I also found that graphql.operations is generic so I can pass in the expected type to get that as the return type for 'data'. Now I just need to understand the code in useQuery and I should be able to work it out. Thanks

Artem Zakharchenko
Artem Zakharchenko(instructor)
~ a month ago

Note that you can pass query and variables type to graphql.operation() as well!

graphql.operation<Query, Variables>(resolver)

Since this handler is meant to handle any GraphQL operations, make sure you provide a union of query and variables types to reflect that.

Give it a try, and if you encounter any difficulties, please reach out to me on GitHub: https://github.com/mswjs/msw/discussions. Thanks!