query()
A request handler that captures a GraphQL query by the given name.
graphql.link()
for the endpoint-based mocking.Call signature
1interface graphql {2 query<QueryType, VariablesType>(3 name: string | RegExp,4 resolver: ResponseResolver,5 ): RequestHandler6}
Examples
Basic query
1query GetAllUsers {2 users {3 firstName4 lastName5 }6}
To capture a GraphQL query provide its name as the first argument to the graphql.query()
request handler. Using the query definition above, the request handler for it would look as follows:
1import { graphql } from 'msw'23graphql.query('GetAllUsers', (req, res, ctx) => {4 return res(5 ctx.data({6 users: [7 {8 firstName: 'John',9 lastName: 'Maverick',10 },11 {12 firstName: 'Cathaline',13 lastName: 'McCoy',14 },15 ],16 }),17 )18})
Query variables
1query GetSingleUser($id: ID!) {2 user(id: $id) {3 firstName4 lastName5 }6}
Variables must be correctly defined in the GraphQL query 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 query.
1graphql.query('GetSingleUser', (req, res, ctx) => {2 const { id } = req.variables34 return res(5 ctx.data({6 user: {7 id,8 firstName: 'John',9 lastName: 'Maverick',10 },11 }),12 )13})
Dynamic query name
When given a RegExp
as the query name, all the GraphQL queries that match that expression would be captured by this request handler.
1query GetUserDetail {2 user {3 firstName4 lastName5 }6}78query GetCartDetail {9 cart {10 id11 items {12 price13 }14 }15}
1import { graphql } from 'msw'23graphql.query(/^Get(.+?)Detail$/, (req, res, ctx) => {4 return res(5 ctx.errors([6 {7 message: 'Not authorized',8 },9 ]),10 )11})
Usage with TypeScript
Annotate your queries in TypeScript to get autocompletion and validation for query data and variables in your IDE.
1import { graphql } from 'msw'23interface GetUserQuery {4 user: {5 firstName: string6 lastName: string7 }8}910interface GetUserQueryVariables {11 id: string12}1314graphql.query<GetUserQuery, GetUserQueryVariables>(15 'GetUser',16 (req, res, ctx) => {17 const { id } = req.variables1819 return res(20 ctx.data({21 user: {22 firstName: 'John',23 lastName: 'Maverick',24 },25 }),26 )27 },28)
Consider tools like GraphQL Code Generator to annotate your mocks with the type definitions derived from the actual GraphQL schema.