Mock Service Worker
  1. Api
  2. graphql
  3. operation()

operation()

A request handler that targets any GraphQL operation, regardless of type or name.

Call signature

1interface graphql {
2 operation(resolver: ResponseResolver): RequestHandler
3}

Examples

Fixed response

1import { graphql } from 'msw'
2
3graphql.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'
3
4const schema = buildSchema(`
5 type Query {
6 hello: String
7 }
8`)
9
10const root = {
11 hello: () => {
12 return 'Hello world!'
13 },
14}
15
16graphql.operation(async (req, res, ctx) => {
17 const payload = await graphqlRequest(
18 schema,
19 req.body.query,
20 root,
21 null,
22 req.variables,
23 )
24
25 return res(ctx.data(payload.data), ctx.errors(payload.errors))
26})