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

testing.md

140 lines4.0 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## 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'));
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 }
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```