Testing (Series)
Understanding Unit Test From The Best Book On The Topic
Testing Ag-Grid React’s Custom Cell Renderer Component
Testing ErrorFallback Component
Testing useDebouncedValue Hook
Testing a HTTP Client Adaptor Hook useClient
Testing a HTTP Error Handler Utility Hook
Testing a Generic Fetch Item List hook with Mock Service
Introducing @mockapi/msw, mock an API server for your entities without writing any code with Mock Service Worker
Testing a Generic Save Item Hook with MSW and @mockapi/msw
Testing a Text Field component integrating Mui’s Text Field with React Hook Form
Subject Under Test(sut)
A HTTP client adaptor that wraps axios’s get, post, patch and delete methods, adding JWT token to all requests if a token is found.
This adaptor hook exists for the following reasons:
- it acts as an adaptor to
axios
, so that in the future, I could replaceaxios
without touching any other code - it adds base URL, JWT and default headers to HTTP calls for conveniences
Behaviours
- the hook returns a set of methods for making HTTP calls
- it prepends base URL
- it adds JWT token to headers if a token is found
- it adds default headers
- it accepts custom headers and overrides default headers
- it accepts custom options and passes them to HTTP requests
Code
Notes
- mock
axios
so that tests don't make actual HTTP calls - JSDOM implements
localstorage
, and there is no need to mock it. setup
usesrenderHook
from@testing-library/react-hooks
, which wraps the hook in a component and return aresult
object withcurrent
property set to whatever the hook returns.setup
also mock the return ofaxios.get
method and returns the mocked axios object for assertions.- included tests only test
get
. Other tests are similar, so they are left out in this blog post for simplicity.
Originally published at https://dev.to on January 11, 2022.