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

testing.md

187 lines5.9 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​
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' })
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>
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>
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 })
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>
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 }
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 ]),
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'