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

testing.md

162 lines4.8 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​
8Writing 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## Our First Test
19​
20Once installed, a simple test can be written. Given the following custom hook:
21​
22```
23export function useCustomHook() {
24 return useQuery('customHook', () => 'Hello');
26```
27​
28We can write a test for this as follows:
29​
30```
31const queryClient = new QueryClient();
32const wrapper = ({ children }) => (
33 <QueryClientProvider client={queryClient}>
34 {children}
35 </QueryClientProvider>
36);
37​
38const { result, waitFor } = renderHook(() => useCustomHook(), { wrapper });
39​
40await waitFor(() => result.current.isSuccess);
41​
42expect(result.current.data).toEqual("Hello");
43```
44​
45Note 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.
46​
47It 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.
48​
49## Turn off retries
50​
51The 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:
52​
53```
54const queryClient = new QueryClient({
55 defaultOptions: {
56 queries: {
57 // βœ… turns retries off
58 retry: false,
59 },
60 },
61})
62const wrapper = ({ children }) => (
63 <QueryClientProvider client={queryClient}>
64 {children}
65 </QueryClientProvider>
66);
67```
68​
69This 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.
70​
71## Testing Network Calls
72​
73The 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.
74​
75There 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).
76​
77Given the following custom hook:
78​
79```
80function useFetchData() {
81 return useQuery('fetchData', () => request('/api/data'));
83```
84​
85We can write a test for this as follows:
86​
87```
88const queryClient = new QueryClient();
89const wrapper = ({ children }) => (
90 <QueryClientProvider client={queryClient}>
91 {children}
92 </QueryClientProvider>
93);
94​
95const expectation = nock('http://example.com')
96 .get('/api/data')
97 .reply(200, {
98 answer: 42
99 });
100​
101const { result, waitFor } = renderHook(() => useFetchData(), { wrapper });
102​
103await waitFor(() => {
104 return result.current.isSuccess;
105});
106​
107expect(result.current).toEqual({answer: 42});
108```
109​
110Here we are making use of `waitFor` and waiting until our the query status indicates that the request has succeeded. This way we know that our hook has finished and should have the correct data.
111​
112## Testing Load More / Infinite Scroll
113​
114First we need to mock our API response
115​
116```
117function generateMockedResponse(page) {
118 return {
119 page: page,
120 items: [...]
121 }
123```
124​
125Then, our `nock` configuration needs to differentiate responses based on the page, and we'll be using `uri` to do this.
126`uri`'s value here will be something like `"/?page=1` or `/?page=2`
127​
128```
129const expectation = nock('http://example.com')
130 .persist()
131 .query(true)
132 .get('/api/data')
133 .reply(200, (uri) => {
134 const url = new URL(`http://example.com${uri}`);
135 const { page } = Object.fromEntries(url.searchParams);
136 return generateMockedResponse(page);
137 });
138```
139​
140(Notice the `.persist()`, because we'll be calling from this endpoint multiple times)
141​
142Now we can safely run our tests, the trick here is to await both `isFetching` and then `!isFetching` after calling `fetchNextPage()`:
143​
144```
145const { result, waitFor } = renderHook(() => useInfiniteQueryCustomHook(), { wrapper });
146​
147await waitFor(() => result.current.isSuccess);
148​
149expect(result.current.data.pages).toStrictEqual(generateMockedResponse(1));
150​
151result.current.fetchNextPage();
152​
153await waitFor(() => result.current.isFetching);
154await waitFor(() => !result.current.isFetching);
155​
156expect(result.current.data.pages).toStrictEqual([
157 ...generateMockedResponse(1),
158 ...generateMockedResponse(2),
159]);
160​
161expectation.done();
162```