Open History to see the last commit
1---
2id: testing
3title: Testing
4---
5β
6React Query works by means of hooks - either the ones we offer or custom ones that wrap around them.
7β
8Writing unit tests for these custom hooks can be done by means of the [React Hooks Testing Library](https://react-hooks-testing-library.com/) library.
9β
10Install this by running:
11β
12```sh
13npm install @testing-library/react-hooks react-test-renderer --save-dev
14```
15β
16(The `react-test-renderer` library is needed as a peer dependency of `@testing-library/react-hooks`, and needs to correspond to the version of React that you are using.)
17β
18## Our First Test
19β
20Once installed, a simple test can be written. Given the following custom hook:
21β
22```
23export function useCustomHook() {
24 return useQuery(['customHook'], () => 'Hello');
25}
26```
27β
28We can write a test for this as follows:
29β
30```
31const queryClient = new QueryClient();
32const wrapper = ({ children }) => (
33 <QueryClientProvider client={queryClient}>
34 {children}
35 </QueryClientProvider>
36);
37β
38const { result, waitFor } = renderHook(() => useCustomHook(), { wrapper });
39β
40await waitFor(() => result.current.isSuccess);
41β
42expect(result.current.data).toEqual("Hello");
43```
44β
45Note that we provide a custom wrapper that builds the `QueryClient` and `QueryClientProvider`. This helps to ensure that our test is completely isolated from any other tests.
46β
47It is possible to write this wrapper only once, but if so we need to ensure that the `QueryClient` gets cleared before every test, and that tests don't run in parallel otherwise one test will influence the results of others.
48β
49## Turn off retries
50β
51The library defaults to three retries with exponential backoff, which means that your tests are likely to timeout if you want to test an erroneous query. The easiest way to turn retries off is via the QueryClientProvider. Let's extend the above example:
52β
53```
54const queryClient = new QueryClient({
55 defaultOptions: {
56 queries: {
57 // β
turns retries off
58 retry: false,
59 },
60 },
61})
62const wrapper = ({ children }) => (
63 <QueryClientProvider client={queryClient}>
64 {children}
65 </QueryClientProvider>
66);
67```
68β
69This will set the defaults for all queries in the component tree to "no retries". It is important to know that this will only work if your actual useQuery has no explicit retries set. If you have a query that wants 5 retries, this will still take precedence, because defaults are only taken as a fallback.
70β
71## Turn off network error logging
72β
73When testing we want to suppress network errors being logged to the console.
74To do this, we can pass a custom logger to `QueryClient`:
75β
76```ts
77import { QueryClient } from 'react-query'
78β
79const queryClient = new QueryClient({
80 logger: {
81 log: console.log,
82 warn: console.warn,
83 // β
no more errors on the console for tests
84 error: process.env.NODE_ENV === 'test' ? () => {} : console.error,
85 },
86})
87```
88β
89## Set cacheTime to Infinity with Jest
90β
91If you use Jest, you can set the `cacheTime` to `Infinity` to prevent "Jest did not exit one second after the test run completed" error message. This is the default behavior on the server, and is only necessary to set if you are explicitly setting a `cacheTime`.
92β
93## Testing Network Calls
94β
95The primary use for React Query is to cache network requests, so it's important that we can test our code is making the correct network requests in the first place.
96β
97There are plenty of ways that these can be tested, but for this example we are going to use [nock](https://www.npmjs.com/package/nock).
98β
99Given the following custom hook:
100β
101```
102function useFetchData() {
103 return useQuery(['fetchData'], () => request('/api/data'));
104}
105```
106β
107We can write a test for this as follows:
108β
109```
110const queryClient = new QueryClient();
111const wrapper = ({ children }) => (
112 <QueryClientProvider client={queryClient}>
113 {children}
114 </QueryClientProvider>
115);
116β
117const expectation = nock('http://example.com')
118 .get('/api/data')
119 .reply(200, {
120 answer: 42
121 });
122β
123const { result, waitFor } = renderHook(() => useFetchData(), { wrapper });
124β
125await waitFor(() => {
126 return result.current.isSuccess;
127});
128β
129expect(result.current.data).toEqual({answer: 42});
130```
131β
132Here we are making use of `waitFor` and waiting until the query status indicates that the request has succeeded. This way we know that our hook has finished and should have the correct data.
133β
134## Testing Load More / Infinite Scroll
135β
136First we need to mock our API response
137β
138```
139function generateMockedResponse(page) {
140 return {
141 page: page,
142 items: [...]
143 }
144}
145```
146β
147Then, our `nock` configuration needs to differentiate responses based on the page, and we'll be using `uri` to do this.
148`uri`'s value here will be something like `"/?page=1` or `/?page=2`
149β
150```
151const expectation = nock('http://example.com')
152 .persist()
153 .query(true)
154 .get('/api/data')
155 .reply(200, (uri) => {
156 const url = new URL(`http://example.com${uri}`);
157 const { page } = Object.fromEntries(url.searchParams);
158 return generateMockedResponse(page);
159 });
160```
161β
162(Notice the `.persist()`, because we'll be calling from this endpoint multiple times)
163β
164Now we can safely run our tests, the trick here is to await both `isFetching` and then `!isFetching` after calling `fetchNextPage()`:
165β
166```
167const { result, waitFor } = renderHook(() => useInfiniteQueryCustomHook(), { wrapper });
168β
169await waitFor(() => result.current.isSuccess);
170β
171expect(result.current.data.pages).toStrictEqual(generateMockedResponse(1));
172β
173result.current.fetchNextPage();
174β
175await waitFor(() => result.current.isFetching);
176await waitFor(() => !result.current.isFetching);
177β
178expect(result.current.data.pages).toStrictEqual([
179 ...generateMockedResponse(1),
180 ...generateMockedResponse(2),
181]);
182β
183expectation.done();
184```
185β
186## Further reading
187β
188For additional tips and an alternative setup using `mock-service-worker`, have a look at [Testing React Query](../community/tkdodos-blog#5-testing-react-query) from
189the Community Resources.