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