Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

testing.md

182 lines5.5 KB

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' })
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>
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>
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 })
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>
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 }
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 ]),
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'