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