Testing a Generic Fetch Item List hook with Mock Service Worker

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.

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.

--

--

.net, Angular, React. Creator of epicerp.app

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store