Testing a Generic Fetch Item List hook with Mock Service Worker

rexebin

Rex

Posted on January 12, 2022

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.

  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.

💖 💪 🙅 🚩
rexebin
Rex

Posted on January 12, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related