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β
8[//]: # 'Install'
9β
10Writing unit tests for these custom hooks can be done by means of the [React Testing Library](https://testing-library.com/docs/react-testing-library/intro/), which provides `renderHook` and re-exports the `@testing-library/dom` helpers such as `waitFor`.
11β
12Install this by running:
13β
14```sh
15npm install @testing-library/react @testing-library/dom --save-dev
16```
17β
18[//]: # 'Install'
19β
20## Our First Test
21β
22Once installed, a simple test can be written. Given the following custom hook:
23β
24```tsx
25export function useCustomHook() {
26 return useQuery({ queryKey: ['customHook'], queryFn: () => 'Hello' })
27}
28```
29β
30We can write a test for this as follows:
31β
32[//]: # 'ExampleFirstTest'
33β
34```tsx
35import { renderHook, waitFor } from '@testing-library/react'
36β
37const queryClient = new QueryClient()
38const wrapper = ({ children }) => (
39 <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
40)
41β
42const { result } = renderHook(() => useCustomHook(), { wrapper })
43β
44await waitFor(() => expect(result.current.isSuccess).toBe(true))
45β
46expect(result.current.data).toEqual('Hello')
47```
48β
49[//]: # 'ExampleFirstTest'
50β
51Note 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.
52β
53It 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.
54β
55## Turn off retries
56β
57The 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:
58β
59```tsx
60const queryClient = new QueryClient({
61 defaultOptions: {
62 queries: {
63 // β
turns retries off
64 retry: false,
65 },
66 },
67})
68const wrapper = ({ children }) => (
69 <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
70)
71```
72β
73This 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.
74β
75## Set gcTime to Infinity with Jest
76β
77If you use Jest, you can set the `gcTime` 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 `gcTime`.
78β
79## Testing Network Calls
80β
81The 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.
82β
83There 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).
84β
85Given the following custom hook:
86β
87```tsx
88function useFetchData() {
89 return useQuery({
90 queryKey: ['fetchData'],
91 queryFn: () => request('/api/data'),
92 })
93}
94```
95β
96We can write a test for this as follows:
97β
98```tsx
99const queryClient = new QueryClient()
100const wrapper = ({ children }) => (
101 <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
102)
103β
104const expectation = nock('http://example.com').get('/api/data').reply(200, {
105 answer: 42,
106})
107β
108const { result } = renderHook(() => useFetchData(), { wrapper })
109β
110await waitFor(() => expect(result.current.isSuccess).toBe(true))
111β
112expect(result.current.data).toEqual({ answer: 42 })
113```
114β
115[//]: # 'NoteWaitFor1'
116β
117Here 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.
118[//]: # 'NoteWaitFor1'
119β
120## Testing Load More / Infinite Scroll
121β
122First we need to mock our API response
123β
124```tsx
125function generateMockedResponse(page) {
126 return {
127 page: page,
128 items: [...]
129 }
130}
131```
132β
133Then, our `nock` configuration needs to differentiate responses based on the page, and we'll be using `uri` to do this.
134`uri`'s value here will be something like `/api/data?page=1` or `/api/data?page=2`
135β
136```tsx
137const expectation = nock('http://example.com')
138 .persist()
139 .get('/api/data')
140 .query(true)
141 .reply(200, (uri) => {
142 const url = new URL(`http://example.com${uri}`)
143 const { page } = Object.fromEntries(url.searchParams)
144 return generateMockedResponse(Number(page))
145 })
146```
147β
148(Notice the `.persist()`, because we'll be calling from this endpoint multiple times)
149β
150Now we can safely run our tests, the trick here is to await for the data assertion to pass:
151β
152```tsx
153const { result } = renderHook(() => useInfiniteQueryCustomHook(), {
154 wrapper,
155})
156β
157await waitFor(() => expect(result.current.isSuccess).toBe(true))
158β
159expect(result.current.data.pages).toStrictEqual([generateMockedResponse(1)])
160β
161result.current.fetchNextPage()
162β
163await waitFor(() =>
164 expect(result.current.data.pages).toStrictEqual([
165 generateMockedResponse(1),
166 generateMockedResponse(2),
167 ]),
168)
169β
170expectation.done()
171```
172β
173[//]: # 'NoteWaitFor2'
174[//]: # 'NoteWaitFor2'
175β
176## Further reading
177β
178[//]: # 'FurtherReading'
179β
180For additional tips and an alternative setup using `mock-service-worker`, have a look at [this article by TkDodo on Testing React Query](https://tkdodo.eu/blog/testing-react-query).
181β
182[//]: # 'FurtherReading'