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

testing.md

171 lines5.7 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​
30We can write a test for this as follows:
31​
32```tsx
33import { renderHook, waitFor } from '@testing-library/react'
34​
35const queryClient = new QueryClient()
36const wrapper = ({ children }) => (
37 <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
39​
40const { result } = renderHook(() => useCustomHook(), { wrapper })
41​
42await waitFor(() => expect(result.current.isSuccess).toBe(true))
43​
44expect(result.current.data).toEqual('Hello')
45```
46​
47Note 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.
48​
49It 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.
50​
51## Turn off retries
52​
53The 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:
54​
55```tsx
56const queryClient = new QueryClient({
57 defaultOptions: {
58 queries: {
59 // βœ… turns retries off
60 retry: false,
61 },
62 },
63})
64const wrapper = ({ children }) => (
65 <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
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## Set gcTime to Infinity with Jest
72​
73If you use Jest, you can set the `gcTime` 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 `gcTime`.
74​
75## Testing Network Calls
76​
77The 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.
78​
79There 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).
80​
81Given the following custom hook:
82​
83```tsx
84function useFetchData() {
85 return useQuery({
86 queryKey: ['fetchData'],
87 queryFn: () => request('/api/data'),
88 })
90```
91​
92We can write a test for this as follows:
93​
94```tsx
95const queryClient = new QueryClient()
96const wrapper = ({ children }) => (
97 <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
99​
100const expectation = nock('http://example.com').get('/api/data').reply(200, {
101 answer: 42,
102})
103​
104const { result } = renderHook(() => useFetchData(), { wrapper })
105​
106await waitFor(() => expect(result.current.isSuccess).toBe(true))
107​
108expect(result.current.data).toEqual({ answer: 42 })
109```
110​
111Here 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.
112​
113## Testing Load More / Infinite Scroll
114​
115First we need to mock our API response
116​
117```tsx
118function generateMockedResponse(page) {
119 return {
120 page: page,
121 items: [...]
122 }
124```
125​
126Then, our `nock` configuration needs to differentiate responses based on the page, and we'll be using `uri` to do this.
127`uri`'s value here will be something like `"/?page=1` or `/?page=2`
128​
129```tsx
130const expectation = nock('http://example.com')
131 .persist()
132 .query(true)
133 .get('/api/data')
134 .reply(200, (uri) => {
135 const url = new URL(`http://example.com${uri}`)
136 const { page } = Object.fromEntries(url.searchParams)
137 return generateMockedResponse(page)
138 })
139```
140​
141(Notice the `.persist()`, because we'll be calling from this endpoint multiple times)
142​
143Now we can safely run our tests, the trick here is to await for the data assertion to pass:
144​
145```tsx
146const { result } = renderHook(() => useInfiniteQueryCustomHook(), {
147 wrapper,
148})
149​
150await waitFor(() => expect(result.current.isSuccess).toBe(true))
151​
152expect(result.current.data.pages).toStrictEqual(generateMockedResponse(1))
153​
154result.current.fetchNextPage()
155​
156await waitFor(() =>
157 expect(result.current.data.pages).toStrictEqual([
158 ...generateMockedResponse(1),
159 ...generateMockedResponse(2),
160 ]),
162​
163expectation.done()
164```
165​
166_Note_: when using React 18, the semantics of `waitFor` have changed as noted above.
167​
168## Further reading
169​
170For additional tips and an alternative setup using `mock-service-worker`, have a look at [Testing React Query](../community/tkdodos-blog.md#5-testing-react-query) from
171the Community Resources.