模拟 GraphQL 模式
当使用 描述 GraphQL API 时,响应解析器返回的响应将按原样发送到客户端,即使它们包含原始查询中不存在的额外属性。虽然这允许开始使用 GraphQL API 而无需定义架构和解析器,但这种行为并不是人们对实际 GraphQL 服务器的期望。
¥When describing GraphQL APIs, the responses returned from response resolvers will be sent to the client as-is, even if they include extra properties not present in the original query. While this allows to get started with a GraphQL API without having to define schemas and resolvers, such behavior is not what one would expect from an actual GraphQL server.
你可以使用 graphql
包根据模拟的 GraphQL 模式解析被拦截的 GraphQL 操作。在下面的例子中,我们还将使用 graphql.operation()
请求处理程序根据架构解析它们。
¥You can resolve intercepted GraphQL operations against a mocked GraphQL schema using the graphql
package. In the example below, we will also use the graphql.operation()
request handler to resolve them against the schema.
import { graphql } from 'msw'
import { graphql as executeGraphql, buildSchema } from 'graphql'
const schema = buildSchema(`
type User {
id: ID!
firstName: String!
}
type Query {
user(id: ID!): User
}
`)
const data = {
users: [
{ id: 1, name: 'John' },
{ id: 2, name: 'Kate' },
]
}
export const handlers = [
graphql.operation(({ query, variables }) => {
const { data, errors } = await executeGraphql({
schema,
source: query,
variableValues: variables,
rootValue: {
user(args) {
return data.users.find((user) => user.id === args.id)
}
}
})
return HttpResponse.json({ errors, data })
})
]