Closed7

MSWでGraphQLってどうやるのん

hajimismhajimism

ほう

import { graphql, HttpResponse } from 'msw'
 
export const handlers = [
  graphql.query('GetUser', ({ query, variables }) => {
    const { userId } = variables
 
    return HttpResponse.json({
      data: {
        user: {
          name: 'John',
        },
      },
    })
  }),
]
hajimismhajimism
hajimismhajimism

In this tutorial, we will describe a basic GraphQL API that covers the following operations:

  • query ListPosts, to return all existing posts;
  • mutation CreatePost, to create a new post;
  • mutation DeletePost, to delete a post by ID.
hajimismhajimism

GraphQL responses, however, have a number of differences:

  • GraphQL responses are always 200 OK, even in case of error responses;
  • GraphQL response bodies must have a fixed structure ({ data, errors, extensions });

知らんかったらミスるやつ

hajimismhajimism

One of the reasons to adopt GraphQL is to fetch only the data the client needs. When mocking the GraphQL responses with MSW, however, the entire mock data will be sent to the client as-is, regardless of the fields it queries.

You can match the behavior of an actual GraphQL server more closely by resolving the intercepted queries using the graphql package. This approach requires you to define the GraphQL schema and forward the operation name, query, and variables of the intercepted GraphQL operations to be resolved against a mock root value.

やっておくか迷うところだな
エラーレスポンス作るのは楽になりそう

このスクラップは6ヶ月前にクローズされました