图QL 测试库 提供便于生成的公用事业 模拟服务工人 任意 GraphQL API 的处理器.
MSW就是那个 测试图书馆推荐 如何在测试中公开模拟API的通信 而不刺耳 window.fetch。 。 。 .
此库目前支持递增的传送功能 @defer 财务报告和审定财务报表 @stream 以及WebSockets等其他运输工具, 目前为MSW的β。 。 。 .
这个项目不属于 "试文库" 激励它的生态系统。 我们只是粉丝:)
安装
这个图书馆 peerDependencies 清单 msw 时间 ^2.0.0 财务报告和审定财务报表 graphql 时间 ^15.0.0 || ^16.0.0。使用您首选的软件包管理器与此库一起安装 :
npm install --save-dev @apollo/graphql-testing-library msw graphql
pnpm add --save-dev @apollo/graphql-testing-library msw graphql
yarn add --dev @apollo/graphql-testing-library msw graphql
bun add --dev @apollo/graphql-testing-library msw graphql
使用量
createHandler
import { createHandler } from "@apollo/graphql-testing-library";
// We suggest using @graphql-tools/mock and @graphql-tools/schema
// to create a schema with mock resolvers.
// See https://the-guild.dev/graphql/tools/docs/mocking for more info.
import { addMocksToSchema } from "@graphql-tools/mock";
import { makeExecutableSchema } from "@graphql-tools/schema";
import typeDefs from "./schema.graphql";
// Create an executable schema
const schema = makeExecutableSchema({ typeDefs });
// Add mock resolvers
const schemaWithMocks = addMocksToSchema({
schema,
resolvers: {
Query: {
products: () =>
Array.from({ length: 5 }, (_element, id) => ({
id: `product-${id}`,
})),
},
},
});
// `createHandler` returns an object with a `handler` and `replaceSchema`
// function: `handler` is a MSW handler that will intercept all GraphQL
// operations, and `replaceSchema` allows you to replace the mock schema
// the `handler` use to resolve requests against.
const { handler, replaceSchema } = createHandler(schemaWithMocks, {
// It accepts a config object as the second argument where you can specify a
// delay duration, which uses MSW's delay API:
// https://mswjs.io/docs/api/delay
// Default: "real" (100-400ms in browsers, 20ms in Node-like processes)
delay: number | "infinite" | "real",
});