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

testing.md

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