Open History to see the last commit
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');
25}
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## Testing Network Calls
50β
51The 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.
52β
53There 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).
54β
55Given the following custom hook:
56β
57```
58function useFetchData() {
59 return useQuery('fetchData', () => request('/api/data'));
60}
61```
62β
63We can write a test for this as follows:
64β
65```
66const queryClient = new QueryClient();
67const wrapper = ({ children }) => (
68 <QueryClientProvider client={queryClient}>
69 {children}
70 </QueryClientProvider>
71);
72β
73const expectation = nock('http://example.com')
74 .get('/api/data')
75 .reply(200, {
76 answer: 42
77 });
78β
79const { result, waitFor } = renderHook(() => useFetchData(), { wrapper });
80β
81await waitFor(() => {
82 return result.current.isSuccess;
83});
84β
85expect(result.current).toEqual({answer: 42});
86```
87β
88Here 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.
89β
90## Testing Load More / Infinite Scroll
91β
92First we need to mock our API response
93β
94```
95function generateMockedResponse(page) {
96 return {
97 page: page,
98 items: [...]
99 }
100}
101```
102β
103Then, our `nock` configuration needs to differentiate responses based on the page, and we'll be using `uri` to do this.
104`uri`'s value here will be something like `"/?page=1` or `/?page=2`
105β
106```
107const expectation = nock('http://example.com')
108 .persist()
109 .query(true)
110 .get('/api/data')
111 .reply(200, (uri) => {
112 const url = new URL(`http://example.com${uri}`);
113 const { page } = Object.fromEntries(url.searchParams);
114 return generateMockedResponse(page);
115 });
116```
117β
118(Notice the `.persist()`, because we'll be calling from this endpoint multiple times)
119β
120Now we can safely run our tests, the trick here is to await both `isFetching` and then `!isFetching` after calling `fetchMore()`:
121β
122```
123const { result, waitFor } = renderHook(() => useInfiniteQueryCustomHook(), { wrapper });
124β
125await waitFor(() => result.current.isSuccess);
126β
127expect(result.current.data).toStrictEqual(generateMockedResponse(1));
128β
129result.current.fetchMore();
130β
131await waitFor(() => result.current.isFetching);
132await waitFor(() => !result.current.isFetching);
133β
134expect(result.current.data).toStrictEqual([
135 ...generateMockedResponse(1),
136 ...generateMockedResponse(2),
137]);
138β
139expectation.done();
140```