Avoid request assertions

When testing, it may be tempting to write assertions against the intercepted request. Examples of such assertions may include:

  • Check that the tested code has performed a certain request;
  • Check that the request was performed with the correct URL/parameters/body/etc;
  • Check that a specific request handler was called.

We highly discourage against such assertions as they represent implementation detail testing and sway you into testing how your application is written instead of what it does. Treat this as the default recommendation when testing with MSW.

Request validity

The best way to assert the request’s validity is faithfully describing its behavior in request handlers.

For example, when describing a login endpoint, you don’t need to assert that the request body contained the email form data field in your test. Instead, return an error response if it didn’t in your request handler:

export const handlers = [
  http.post('/login', async ({ request }) => {
    const data = await request.formData()
    const email = data.get('email')
 
    if (!email) {
      return new HttpResponse('Missing email', { status: 400 })
    }
  }),
]

Not only is this the right way to assert the request’s validity, error handling also brings your request handlers closer to the production behavior.

If the tested code happens to miss the email key its FormData body, your application will receive an error response, making your UI-based assertions fail, indicating an issue.

This stands true for a more targeted tests as well since you can specify additional request handler logic using network overrides on a per-test basis.

Unhandled requests

To make sure your tested code doesn’t perform any unknown HTTP requests, use the onUnhandledRequest option of the worker.start()/server.listen():

server.listen({
  // This tells MSW to throw an error whenever it
  // encounters a request that doesn't have a
  // matching request handler.
  onUnhandledRequest: 'error',
})

This is particularly useful option to set in your test setup file.

Exceptions

That being said, there are scenarios when a performed request has no indication in the application that can be asserted. These are usually one-way requests against third-party services, like analytics or monitoring.

For those cases, please use the Life-cycle events API to provide direct assertions on requests/responses.