Testing a Generic Save Item Hook with MSW and @mockapi/msw

Rex Ye
2 min readJan 17, 2022

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

A generic hook wrapping useMutation of React-Query for all of my master-detail edit forms. It is an adaptor responsible for generating URL by entity name, error handling and invalidating relevant queries.

Behaviours

  1. it takes an entityName and generates the correct URL to send a post request to
  2. it forwards models and request configurations to the HTTP request
  3. it wires up ErrorHandler for error handling
  4. it invalidates queries with keys containing the entityName

MSW and @mockapi/msw

The tests use MSW and @mockapi/msw to mock a post endpoint for a dummy entity Supplier. @mockapi/msw provides a standard set of CRUD endpoints so that I do not have to write any endpoints for this test suite. For more information: @mockapi/msw

Code

Notes

  1. TestComponent shows how the SUT is to be used. It also has a useGetItems hook to test if the queries are invalidated properly. The code and tests for useGetItems are here, it also introduced the use of useTranslationForTest and QueryClientProviderForTest
  2. the tests uses findByText as a way to wait for the SUT to finish its operations
  3. server.use from MSW is used to override the target endpoint to test the params and error responses.
  4. With the help of MSW, the tests only care about the data flows. I love the setup because it doesn’t care about how the HTTP requests are made. I could have replaced React Query and Axios without touching the tests.

Originally published at https://dev.to on January 17, 2022.

--

--