Testing a Generic Fetch Item List hook with Mock Service Worker
Rex
Posted on January 12, 2022
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
it takes a required
entityName
option to determine which API endpoint to make the HTTP call.it takes an optional
queryKey
as the query key ofuseQuery
fromReact-Query
. The query key is used to invalidate the query cache when appropriate to show the latest data for the users.it takes an optional
requestConfig
of typeAxiosRequestConfig
to be passed to the HTTP call. So that components can add params to the HTTP request.it takes an optional
t
to translate the error message.it sends error messages to the Message Context.
Mocks
-
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.
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
TestComponent
shows how the SUT is to be used.the template of
TestComponent
is designed specifically for the tests.isSuccess
andisError
ensure that the elements are only shown when the HTTP calls are done, making the tests short and straightforward.TestComponent
uses the hook's params as its props so that the tests can customise most of the options outside of the component.only unmanaged dependencies are mocked: API server and Localisation(because it requires API calls to get dictionary).
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.
Posted on January 12, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.