mutation()
A request handler that captures a GraphQL mutation by the given name.
graphql.link()
for the endpoint-based mocking.Call signature
1interface graphql {2 mutation<MutationType, VariablesType>(3 name: string | RegExp,4 resolver: ResponseResolver,5 ): RequestHandler6}
Examples
Basic mutation
1mutation Logout {2 user {3 sessionId4 }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'23graphql.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 sessionId4 }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'23graphql.mutation('Logout', (req, res, ctx) => {4 const { username, password } = req.variables56 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 id4 }5}67mutation DeleteUser {8 user {9 id10 }11}
1import { graphql } from 'msw'23graphql.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'23interface LoginMutation {4 user: {5 firstName: string6 lastName: string7 }8}910interface LoginMutationVariables {11 username: string12 password: string13}1415graphql.mutation<LoginMutation, LoginMutationVariables>(16 'Login',17 (req, res, ctx) => {18 const { username, password } = req.variables1920 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.