Testing a Generic Fetch Item List hook with Mock Service Worker

Rex Ye
2 min readJan 12, 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 fetch item list hook used to fetch data from the API server, designed for a generic item list component template, part of a set of generic CRUD templates/schematics that I use for most of my entities.

Behaviours

  1. it takes a required entityName option to determine which API endpoint to make the HTTP call.
  2. it takes an optional queryKey as the query key of useQuery from React-Query. The query key is used to invalidate the query cache when appropriate to show the latest data for the users.
  3. it takes an optional requestConfig of type AxiosRequestConfig to be passed to the HTTP call. So that components can add params to the HTTP request.
  4. it takes an optional t to translate the error message.
  5. it sends error messages to the Message Context.

Mocks

  1. Mock Service Worker
    The test uses MSW to mock the API calls and respond appropriately for the tests. The mocked API code is as below.

2. useTranslationForTest.ts is a test double to replace the real localisation solution that requires loading dictionaries from a remote API server.

Common Test Setup

QueryClientProviderForTest.ts is used to test all React-Query hooks.

Code

Notes

  1. TestComponent shows how the SUT is to be used.
  2. the template of TestComponent is designed specifically for the tests. isSuccess and isError ensure that the elements are only shown when the HTTP calls are done, making the tests short and straightforward.
  3. TestComponent uses the hook's params as its props so that the tests can customise most of the options outside of the component.
  4. only unmanaged dependencies are mocked: API server and Localisation(because it requires API calls to get dictionary).
  5. I debated if the SUT is too trivial to test because it is a wrapper of useQuery and contains hardly any logic. I decided to write the tests because the SUT has been used heavily.

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

--

--