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

testing.md

201 lines6.4 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​
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' })
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>
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>
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## Turn off network error logging
82​
83When testing we want to suppress network errors being logged to the console.
84To do this, we can pass a custom logger to `QueryClient`:
85​
86```tsx
87import { QueryClient } from '@tanstack/react-query'
88​
89const queryClient = new QueryClient({
90 logger: {
91 log: console.log,
92 warn: console.warn,
93 // βœ… no more errors on the console for tests
94 error: process.env.NODE_ENV === 'test' ? () => {} : console.error,
95 },
96})
97```
98​
99## Set cacheTime to Infinity with Jest
100​
101If you use Jest, you can set the `cacheTime` 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 `cacheTime`.
102​
103## Testing Network Calls
104​
105The 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.
106​
107There 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).
108​
109Given the following custom hook:
110​
111```tsx
112function useFetchData() {
113 return useQuery({
114 queryKey: ['fetchData'],
115 queryFn: () => request('/api/data'),
116 })
118```
119​
120We can write a test for this as follows:
121​
122```tsx
123const queryClient = new QueryClient()
124const wrapper = ({ children }) => (
125 <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
127​
128const expectation = nock('http://example.com').get('/api/data').reply(200, {
129 answer: 42,
130})
131​
132const { result, waitFor } = renderHook(() => useFetchData(), { wrapper })
133​
134await waitFor(() => {
135 return result.current.isSuccess
136})
137​
138expect(result.current.data).toEqual({ answer: 42 })
139```
140​
141Here 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.
142​
143## Testing Load More / Infinite Scroll
144​
145First we need to mock our API response
146​
147```tsx
148function generateMockedResponse(page) {
149 return {
150 page: page,
151 items: [...]
152 }
154```
155​
156Then, our `nock` configuration needs to differentiate responses based on the page, and we'll be using `uri` to do this.
157`uri`'s value here will be something like `"/?page=1` or `/?page=2`
158​
159```tsx
160const expectation = nock('http://example.com')
161 .persist()
162 .query(true)
163 .get('/api/data')
164 .reply(200, (uri) => {
165 const url = new URL(`http://example.com${uri}`)
166 const { page } = Object.fromEntries(url.searchParams)
167 return generateMockedResponse(page)
168 })
169```
170​
171(Notice the `.persist()`, because we'll be calling from this endpoint multiple times)
172​
173Now we can safely run our tests, the trick here is to await for the data assertion to pass:
174​
175```tsx
176const { result, waitFor } = renderHook(() => useInfiniteQueryCustomHook(), {
177 wrapper,
178})
179​
180await waitFor(() => result.current.isSuccess)
181​
182expect(result.current.data.pages).toStrictEqual(generateMockedResponse(1))
183​
184result.current.fetchNextPage()
185​
186await waitFor(() =>
187 expect(result.current.data.pages).toStrictEqual([
188 ...generateMockedResponse(1),
189 ...generateMockedResponse(2),
190 ]),
192​
193expectation.done()
194```
195​
196_Note_: when using React 18, the semantics of `waitFor` have changed as noted above.
197​
198## Further reading
199​
200For 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
201the Community Resources.