Testing a HTTP Error Handler Utility Hook

Subject Under Test

A utility hook provides an HTTP error handler that sends errors to a message context. A message snack bar component would show errors in toasters for end users.


  1. it takes an optional message to be prepended to error messages returned from the server
  2. it takes an optional translator for localisation
  3. it clears the JWT token if the server returns 401 Unauthorised Error
  4. it sends an error alerting the user to log in to an account with the required permissions if the server returns 403 Unauthorised Error
  5. it sends extract error messages from response.data when applicable
  6. it sends “Server connection failed” if no response is received
  7. if the above fails, it logs out error as-is in the console



  1. TestComponent shows a way the error handler hook could be used. It is a component designed to facilitate the tests.
  2. setup function mocks axios and renders the above component inside a MessageProvider which is not mocked.
  3. userEvent is used to trigger the HTTP call, which was mocked to reject with an error object. It has to be wrapped inside an act block as it updates the states in the message context.
  4. findBy queries from @testing-library is async by design, and we do not have to do anything extra in the tests to wait for async operations.
  5. in the last test, I use `waitFor` from `@testing-library` as there is nothing be found by `findBy`. Note: do not forget to `await` for `waitFor` as I did.



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store