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

query()

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

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

Call signature

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

Examples

Basic query

1query GetAllUsers {
2 users {
3 firstName
4 lastName
5 }
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'
2
3graphql.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 firstName
4 lastName
5 }
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.variables
3
4 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 firstName
4 lastName
5 }
6}
7
8query GetCartDetail {
9 cart {
10 id
11 items {
12 price
13 }
14 }
15}
1import { graphql } from 'msw'
2
3graphql.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'
2
3interface GetUserQuery {
4 user: {
5 firstName: string
6 lastName: string
7 }
8}
9
10interface GetUserQueryVariables {
11 id: string
12}
13
14graphql.query<GetUserQuery, GetUserQueryVariables>(
15 'GetUser',
16 (req, res, ctx) => {
17 const { id } = req.variables
18
19 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.