Mocking GraphQL responses

响应被拦截的 GraphQL 操作。

由于 GraphQL 仍然通过 HTTP 实现,因此你可以像处理任何其他 HTTP 请求一样在 相同方式 中处理被拦截的 GraphQL 操作。这包括模拟响应、按原样执行操作或不执行任何操作。

¥Since GraphQL is still implemented over HTTP, you can handle an intercepted GraphQL operation in the same ways as you would any other HTTP request. This includes mocking the response, performing the operation as-is, or doing nothing.

本页将重点介绍如何使用模拟响应来响应 GraphQL 操作。探索左侧部分,找到更多经过微调的模拟场景。

¥This page will focus on responding to GraphQL operations with mocked responses. Explore the section on the left to find more fine-tuned mocking scenarios.

响应声明

¥Response declaration

处理操作时,GraphQL 客户端期望收到预定义格式的 JSON 响应,包括 dataerrors 等属性。在构建模拟响应时,你也必须遵循该格式。

¥When handling operations, GraphQL clients expect a JSON response of a predefined shape, including properties like data, errors, and others. You must respect that shape when constructing your mocked responses as well.

使用 HttpResponse.json() 简写来响应被拦截的 GraphQL 操作。

¥Use the HttpResponse.json() shorthand to respond to an intercepted GraphQL operation.

import { graphql, HttpResponse } from 'msw'
 
const api = graphql.link('https://api.example.com/graphql')
 
type User = {
  id: string
  name: string
}
 
export const handlers = [
  api.query<User, { id: string }>('GetUser', ({ variables }) => {
    return HttpResponse.json({
      data: {
        user: {
          id: variables.id,
          name: 'John Maverick',
        },
      },
    })
  }),
]

包含根级键(例如 dataerrors)以利用不同的 GraphQL 客户端响应处理方案。请记住,GraphQL API 支持部分响应。

¥Include the root-level keys like data or errors to tap into different GraphQL client response handling scenarios. Remember that GraphQL APIs support partial responses.

客户端特定键

¥Client-specific keys

某些 GraphQL 客户端(例如 Apollo)需要响应对象中存在特殊键才能正确处理相关操作。你还必须在模拟响应中包含这些键。有关 GraphQL 客户端如何处理响应以及它是否提供任何辅助函数来简化模拟声明的更多信息,请参阅你的 GraphQL 客户端文档。

¥Some GraphQL clients, like Apollo, require the presence of special keys in the response object to handle the associated operations correctly. You would have to include those keys in your mocked responses as well. Consult your GraphQL client documentation for more information on how it handles responses and whether it provides any helper functions to simplify the mocks declaration for you.

api.query<User>('GetUser', () => {
  return HttpResponse.json({
    data: {
      user: {
        __typename: 'User',
        id: 'abc-123',
        name: 'John Maverick',
      },
    },
  })
})

以上是在 Apollo 所需的模拟响应中包含 __typename 键的示例。

¥Above is an example of including the __typename key in the mocked response reqiured by Apollo.

后续步骤

¥Next steps

在模拟 GraphQL API 方面,你可以做很多事情。请查看本节中列出的方案集合。以下是一些值得注意的参数:

¥There is a lot you can do when it comes to mocking GraphQL APIs. Please take a look at the collection of recipes listed in this section. Here are a few noteworthy ones: