LOGOMock Service Worker
  1. Api
  2. graphql
  3. mutation()

mutation()

A request handler that captures a GraphQL mutation by the given name.

This request handler captures GraphQL mutations regardless of their endpoint. See graphql.link() for the endpoint-based mocking.

Call signature

1interface graphql {
2 mutation<MutationType, VariablesType>(
3 name: string | RegExp,
4 resolver: ResponseResolver,
5 ): RequestHandler
6}

Examples

Basic mutation

1mutation Logout {
2 user {
3 sessionId
4 }
5}

To capture a GraphQL mutation provide its name as the first argument to the graphql.mutation() request handler. Using the mutation definition above, the request handler for it would look as follows:

1import { graphql } from 'msw'
2
3graphql.mutation('Logout', (req, res, ctx) => {
4 return res(
5 ctx.data({
6 user: {
7 sessionId: 'abc-123',
8 },
9 }),
10 )
11})

Mutation variables

1mutation Login($username: String!, $password: String!) {
2 login(username: $username, password: $password) {
3 sessionId
4 }
5}

Variables must be correctly defined in the GraphQL mutation definition in order to be accessible in mocks. Refer to the GraphQL Variables for more information.

Use req.variables object to access all the variables of the captured mutation.

1import { graphql } from 'msw'
2
3graphql.mutation('Logout', (req, res, ctx) => {
4 const { username, password } = req.variables
5
6 return res(
7 ctx.data({
8 login: {
9 sessionId: 'abc-123',
10 },
11 }),
12 )
13})

Dynamic mutation name

When given a RegExp as the mutation name, all the GraphQL mutations that match that expression would be captured by this request handler.

1mutation CreateUser {
2 user {
3 id
4 }
5}
6
7mutation DeleteUser {
8 user {
9 id
10 }
11}
1import { graphql } from 'msw'
2
3graphql.mutation(/^(.+?)User$/, (req, res, ctx) => {
4 return res(
5 ctx.errors([
6 {
7 message: 'Not authorized',
8 },
9 ]),
10 )
11})

Usage with TypeScript

Annotate your mutations in TypeScript to get autocompletion and validation for mutation data and variables in your IDE.

1import { graphql } from 'msw'
2
3interface LoginMutation {
4 user: {
5 firstName: string
6 lastName: string
7 }
8}
9
10interface LoginMutationVariables {
11 username: string
12 password: string
13}
14
15graphql.mutation<LoginMutation, LoginMutationVariables>(
16 'Login',
17 (req, res, ctx) => {
18 const { username, password } = req.variables
19
20 return res(
21 ctx.data({
22 user: {
23 firstName: 'John',
24 lastName: 'Maverick',
25 },
26 }),
27 )
28 },
29)

Consider tools like GraphQL Code Generator to annotate your mocks with the type definitions derived from the actual GraphQL schema.