Mocking GraphQL

拦截和模拟 GraphQL 操作。

Mock Service Worker 提供对模拟 GraphQL API 的一流支持。你可以使用 msw 导出的 graphql 命名空间来开发、测试、展示和调试你的 GraphQL 应用。

¥Mock Service Worker comes with the first-class support for mocking GraphQL APIs. You can develop, test, showcase, and debug your GraphQL applications using the graphql namespace exported by msw.

import { graphql } from 'msw'

graphql

API reference for the `graphql` namespace.

GraphQL 客户端

¥GraphQL clients

MSW 支持拦截任何符合 GraphQL 规范 的 GraphQL 操作。这包括查询和突变(订阅即将推出),无论执行它们的 GraphQL 客户端是什么。无论你是通过 graphql-request 或普通 fetch() 探索 GraphQL,还是使用 Apollo、Relay 或 URQL 等可用于生产的客户端,该库都能满足你的需求。

¥MSW supports intercepting any GraphQL operations that comply with the GraphQL Specification. This includes queries and mutations (subscriptions are coming in the future) regardless of the GraphQL client that performed them. The library has you covered if you’re exploring GraphQL via graphql-request or plain fetch() as well as if you’re using a production-ready client like Apollo, Relay, or URQL.

优点

¥Benefits

以下是使用 MSW 模拟 GraphQL 的一些好处:

¥Here are some of the benefits when using MSW for mocking GraphQL:

  • 不再使用 <MockProvider>!采用更简洁的测试设置,专注于最重要的事情:测试你的应用。

    ¥No more <MockProvider>s! Embrace a cleaner test setup to focus on what matters most: testing your app.

  • 符合规范。该库将拒绝违反规范的操作,这会为你的应用添加一层额外的隐式测试(我们实际上使用 graphql 包来解析操作)。

    ¥Specification-compliant. The library will refuse operations that violate the spec, which adds an extra layer of implicit testing to your application (we literally use the graphql package to parse operations).

  • 与客户端无关。如果你迁移到其他 GraphQL 客户端,则无需修改任何模拟代码。

    ¥Client-agnostic. You won’t have to touch a single line of mocks if you migrate to a different GraphQL client.

  • 类型安全。在模拟中重用 GraphQL 代码生成器 等工具中的类型定义。不再使用过时的模拟。

    ¥Type-safe. Reuse the type definitions you have from tools like GraphQL Code Generator in your mocks. No more out-of-date mocks.

后续步骤

¥Next steps

以下部分将指导你了解有关拦截和模拟 GraphQL API 的所有知识:

¥The following sections will guide you through everything you need to know about intercepting and mocking GraphQL APIs: