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.datawhen 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
TestComponentshows a way the error handler hook could be used. It is a component designed to facilitate the tests.setupfunction mocksaxiosand renders the above component inside aMessageProviderwhich is not mocked.userEventis used to trigger the HTTP call, which was mocked to reject with an error object. It has to be wrapped inside anactblock as it updates the states in the message context.findByqueries from@testing-libraryis 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
waitForfrom@testing-libraryas there is nothing be found byfindBy. Note: do not forget to await forwaitForas I did.
Top comments (2)
Thanks ... testing is often neglected and its hard to find good reading material on it .. appreciated :)
You are welcome. I am glad you liked it. There are a lot of misconceptions out there for testing, but also loads of good ones. Just that if one doesn’t have a good understanding of the principles of testing, it is not easy to recognise one.
If you look for a good testing book to read, read this one: manning.com/books/unit-testing. I think principles are at the core of effective testing.
I know testing is important but have been putting it off for so long, because I didn’t have a concrete understanding of what’s the correct way and to be frank I was confused. The book helped me tremendously.