operation()
A request handler that targets any GraphQL operation, regardless of type or name.
Call signature
1interface graphql {2 operation(resolver: ResponseResolver): RequestHandler3}
Examples
Fixed response
1import { graphql } from 'msw'23graphql.operation((req, res, ctx) => {4 return res(5 ctx.errors([6 {7 message: 'Access denied',8 positions: [1, 92],9 },10 ]),11 )12})
Resolve against schema
You can resolve any operation against a predefined schema, opposed to a fixed response. Here's an example of using the graphql
package to resolve an operation against a predefined schema
:
1import { graphql as graphqlRequest, buildSchema } from 'graphql'2import { graphql } from 'msw'34const schema = buildSchema(`5 type Query {6 hello: String7 }8`)910const root = {11 hello: () => {12 return 'Hello world!'13 },14}1516graphql.operation(async (req, res, ctx) => {17 const { query } = await req.json()18 const payload = await graphqlRequest(schema, query, root, null, req.variables)1920 return res(ctx.data(payload.data), ctx.errors(payload.errors))21})