How to make assertions on graphql query variables when using Mock Service Worker?

1.1k Views Asked by At

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: [],
        },
      })
    );
  })
1

There are 1 best solutions below

0
On

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(...)
})