Testing a HTTP Error Handler Utility Hook
Rex
Posted on January 11, 2022
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.
Behaviours
it takes an optional message to be prepended to error messages returned from the server
it takes an optional translator for localisation
it clears the JWT token if the server returns 401 Unauthorised Error
it sends an error alerting the user to log in to an account with the required permissions if the server returns 403 Unauthorised Error
it sends extract error messages from
response.data
when applicableit sends "Server connection failed" if no response is received
if the above fails, it logs out error as-is in the console
Code
Notes
TestComponent
shows a way the error handler hook could be used. It is a component designed to facilitate the tests.setup
function mocksaxios
and renders the above component inside aMessageProvider
which is not mocked.userEvent
is used to trigger the HTTP call, which was mocked to reject with an error object. It has to be wrapped inside anact
block as it updates the states in the message context.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.in the last test, I use
waitFor
from@testing-library
as there is nothing be found byfindBy
. Note: do not forget to await forwaitFor
as I did.
Posted on January 11, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.