1

When we are mocking out a graphql query with a mock service worker (MSW), we want to assert that the variables passed to the query have certain values. This goes beyond the type validation with the typescript typings. We are using jest with MSW. Do you spy on MSW to make those assertions? or is there another way to expect req.variables to have a certain value.

graphql.query<SaveContent, SaveContentVariables>('SaveContent', (req, res, ctx) => {
    return res(
      ctx.data({
        saveContent: {
          success: true,
          id: req.variables.id,
          errors: [],
        },
      })
    );
  })
Lin Du
  • 88,126
  • 95
  • 281
  • 483
Josh Birdwell
  • 745
  • 4
  • 21
  • TypeScript typings should work if you pass `SaveContentVariables` type to `graphql.query` generic function – Lin Du Dec 10 '20 at 03:43
  • See https://mswjs.io/docs/api/graphql/query#usage-with-typescript – Lin Du Dec 10 '20 at 03:49
  • I'm wanting to check the value was a specific value and not the shape. So that it has these items in the array and not that it was simply an array. – Josh Birdwell Dec 10 '20 at 14:26

1 Answers1

0

Mock Service Worker recommends basing your request assertions on the UI (read more in the Request assertions recipe). In most cases, if your request/response data is correct, then your UI would be correct in the test. The same is true for the opposite scenario. Always assert the data-driven UI, when you can.

In your case, you wish to assert the query variables in a request. Consider returning data based on those variables that later result in a corresponding UI.

When you find it absolutely necessary to perform direct request/response assertions apart from the UI, use the Life-cycle events that allow executing arbitrary logic in response to various MSW events. For example, this is how you can assert request variables in your test:

const server = setupServer(...handlers)

it('saves the content', async () => {
  expect.assertions(1)

  server.on('request:match', (req) => {
    expect(req.variables).toEqual({ id: 'abc-123' })
  })

  await performQuery(...)
})
kettanaito
  • 974
  • 5
  • 12