graphql

拦截 GraphQL API 请求。

graphql 命名空间可帮助你创建请求处理程序来拦截对 GraphQL API 的请求。

¥The graphql namespace helps you create request handlers to intercept requests to a GraphQL API.

调用签名

¥Call signature

graphql.query<Query, Variables>(
  query: string | RegExp | DocumentNode | TypedDocumentNode,
  resolver: ResponseResolver<
    GraphQLResolverExtras<Variables>,
    null,
    GraphQLResponseBody<Query>
  >,
  options?: RequestHandlerOptions
)

graphql.ts

Source code for the `graphql` namespace.

标准方法

¥Standard methods

graphql 命名空间包含代表 GraphQL 操作类型的键(例如 “query”、“mutation”)。

¥The graphql namespace contains keys that represent GraphQL operation types (e.g. “query”, “mutation”).

graphql.query(queryName, resolver)

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

上面的处理程序将拦截并模拟对以下 GraphQL 查询的响应:

¥The handler above will intercept and mock the response to the following GraphQL query:

query GetUser($userId: String!) {
  user(id: $userId) {
    name
  }
}

queryName 参数也可以是 TypedDocumentNode 实例。这意味着你可以在使用 GraphQL 代码生成器 等工具时将基于 GraphQL 操作生成的文档类型直接传递给 MSW。

¥The queryName argument can also be a TypedDocumentNode instance. This means you can pass the generated document types based on your GraphQL operations directly to MSW when using tools like GraphQL Code Generator.

import { graphql, HttpResponse } from 'msw'
import { GetUserDocument } from './generated/types'
 
graphql.query(GetUserDocument, ({ query, variables }) => {
  return HttpResponse.json({
    data: {
      user: {
        id: '75a22f38-c27c-4684-9bdf-d4b16435af1a',
        name: 'John',
      },
    },
  })
})

MSW 将从给定的文档节点推断查询和变量类型。

¥MSW will infer the query and variable types from the given document node.

graphql.mutation(mutationName, resolver)

import { graphql, HttpResponse } from 'msw'
 
export const handlers = [
  graphql.mutation('CreateUser', ({ query, variables }) => {
    const { input } = variables
 
    return HttpResponse.json({
      data: {
        user: {
          name: input.name,
        },
      },
    })
  }),
]

上面的处理程序将拦截并模拟对以下 GraphQL 突变的响应:

¥The handler above will intercept and mock the response to the following GraphQL mutation:

mutation CreateUser($userInput: CreateUserInput!) {
  createUser(input: $userInput) {
    name
  }
}

mutationName 参数也可以是 TypedDocumentNode 实例。这意味着你可以在使用 GraphQL 代码生成器 等工具时将基于 GraphQL 操作生成的文档类型直接传递给 MSW。

¥The mutationName argument can also be a TypedDocumentNode instance. This means you can pass the generated document types based on your GraphQL operations directly to MSW when using tools like GraphQL Code Generator.

import { graphql, HttpResponse } from 'msw'
import { CreateUserDocument } from './generated/types'
 
graphql.mutation(CreateUserDocument, ({ variables }) => {
  return HttpResponse.json({
    data: {
      user: {
        name: variables.input.name,
      },
    },
  })
})

自定义方法

¥Custom methods

graphql 命名空间还包含特殊键,这些键可为你提供附加功能,但不对应于任何 GraphQL 操作类型。

¥The graphql namespace also contains special keys that provide you with additional functionality but do not correspond to any GraphQL operation types.

graphql.link(url)

.link() 方法返回 graphql 命名空间的子集,以拦截作用域为所提供端点的 GraphQL 操作。你可以使用此方法消除 GraphQL 操作之间的歧义。

¥The .link() method returns a subset of the graphql namespace to intercept GraphQL operations scoped to the provided endpoint. You can use this method to disambiguate between GraphQL operations.

import { graphql, HttpResponse } from 'msw'
 
const github = graphql.link('https://api.github.com/graphql')
const stripe = graphql.link('https://api.stripe.com/graphql')
 
export const handlers = [
  github.query('GetPayment', () => {
    return HttpResponse.json({
      data: {
        payment: {
          id: 'e16fded7-64eb-4b69-b4bd-5345507a5a92',
          issuer: { login: 'octocat' },
        },
      },
    })
  }),
  stripe.query('GetPayment', () => {
    return HttpResponse.json({
      errors: [{ message: 'Cannot process payment' }],
    })
  }),
]

尽管 GetPayment 查询的名称相同,但根据请求的端点,它将以不同的方式处理。

¥Although the name of the GetPayment query is the same, it will be handled differently depending on the requested endpoint.

graphql.operation(resolver)

.operation() 方法拦截所有 GraphQL 操作,无论其类型和名称如何。它旨在涵盖以下场景:

¥The .operation() method intercepts all GraphQL operations regardless of their type and name. It’s designed to cover the following scenarios:

  • 处理匿名 GraphQL 操作;

    ¥Handling of anonymous GraphQL operations;

  • 针对 模拟 GraphQL 模式 解决任何传出的 GraphQL 操作。

    ¥Resolving any outgoing GraphQL operations against a mock GraphQL schema.

import { graphql, HttpResponse } from 'msw'
 
export const handlers = [
  graphql.operation(({ query, variables }) => {
    // Intercept all GraphQL operations and respond
    // to them with the error response.
    return HttpResponse.json({
      errors: [{ message: 'Request failed' }],
    })
  }),
]

解析器参数

¥Resolver argument

每个 graphql.* 方法的响应解析器函数在其参数对象中都有以下键:

¥The response resolver function for every graphql.* method has the following keys in its argument object:

名称类型描述
queryobject从客户端发送的 GraphQL 查询。
variablesobject此 GraphQL 查询的变量。
operationNamestring操作名称(例如 GetUser)。
requestRequest整个请求参考。
cookiesobject请求的 cookies

你可以在响应解析器参数对象上访问这些参数。

¥You access these arguments on the response resolver argument object.

graphql.query('GetUser', ({ query, variables, operationName, request }) => {})

处理程序选项

¥Handler options

http 命名空间的所有方法都接受一个可选的第三个参数,该参数表示请求处理程序选项。请参阅下面的选项对象支持的属性列表。

¥All methods of the http namespace accept an optional third argument representing request handler options. See below for the list of supported properties on that options object.

once

  • boolean

如果设置为 true,则在第一次成功匹配后将此请求处理程序标记为已使用。使用的请求处理程序对传出流量没有影响,并且在请求拦截期间将被忽略。

¥If set to true, marks this request handler as used after the first successful match. Used request handlers have no effect on the outgoing traffic and will be ignored during request interception.

graphql.query(
  'GetUser',
  () => {
    return HttpResponse.json({
      data: {
        user: { name: 'John' },
      },
    })
  },
  {
    once: true,
  }
)

worker/server 实例上使用 .restoreHandlers() 方法将所有使用的请求处理程序标记为未使用。

¥Use the .restoreHandlers() method on the worker/server instance to mark all used request handlers as unused.

相关材料

¥Related materials

Describing GraphQL API

Learn about describing GraphQL APIs.