React Query
React Query
Questions around the testing topic come up quite often together with React Query, so I'll try to answer
some of them here. I think one reason for that is that testing "smart" components (also called container
components) is not the easiest thing to do. With the rise of hooks, this split has been largely deprecated. It
is now encouraged to consume hooks directly where you need them rather than doing a mostly arbitrary
split and drill props down.
I think this is generally a very good improvement for colocation and code readability, but we now have
more components that consume dependencies outside of "just props".
They might useContext . They might useSelector . Or they might useQuery .
Those components are technically no longer pure, because calling them in different environments leads to
different results. When testing them, you need to carefully setup those surrounding environments to get
things working.
Mocking network requests
Since React Query is an async server state management library, your components will likely make requests
to a backend. When testing, this backend is not available to actually deliver data, and even if, you likely
don't want to make your tests dependent on that.
There are tons of articles out there on how to mock data with jest. You can mock your api client if you have
one. You can mock fetch or axios directly. I can only second what Kent C. Dodds has written in his article
Stop mocking fetch:
Use mock service worker by @ApiMocking
It can be your single source of truth when it comes to mocking your apis:
works in node for testing
supports REST and GraphQL
has a storybook addon so you can write stories for your components that useQuery
works in the browser for development purposes, and you'll still see the requests going out in the
browser devtools
works with cypress, similar to fixtures
With our network layer being taken care of, we can start talking about React Query specific things to keep
an eye on:
QueryClientProvider
Whenever you use React Query, you need a QueryClientProvider and give it a queryClient - a vessel which
holds the QueryCache . The cache will in turn hold the data of your queries.
I prefer to give each test its own QueryClientProvider and create a new QueryClient for each test. That
way, tests are completely isolated from each other. A different approach might be to clear the cache after
each test, but I like to keep shared state between tests as minimal as possible. Otherwise, you might get
unexpected and flaky results if you run your tests in parallel.
For custom hooks
If you are testing custom hooks, I'm quite certain you're using react-hooks-testing-library. It's the easiest
thing there is to test hooks. With that library, we can wrap our hook in a wrapper, which is a React
component to wrap the test component in when rendering. I think this is the perfect place to create the
QueryClient, because it will be executed once per test:
wrapper
TSX Copy
1 const createWrapper = () => {
2 // ✅ creates a new QueryClient for each test
3 const queryClient = new QueryClient()
4 return ({ children }) => (
5 <QueryClientProvider client={queryClient}>
6 {children}
7 </QueryClientProvider>
8 )
9 }
10
11 test('my first test', async () => {
12 const { result } = renderHook(() => useCustomHook(), {
13 wrapper: createWrapper(),
14 })
15 })
For components
If you want to test a Component that uses a useQuery hook, you also need to wrap that Component in
QueryClientProvider. A small wrapper around render from react-testing-library seems like a good choice.
Have a look at how React Query does it internally for their tests.
Turn off retries
It's one of the most common "gotchas" with React Query and testing: The 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, again, via the QueryClientProvider . Let's extend the above
example:
no-retries
TSX Copy
1 const createWrapper = () => {
2 const queryClient = new QueryClient({
3 defaultOptions: {
4 queries: {
5 // ✅turns retries off
6 retry: false,
7 },
8 },
9 })
10
11 return ({ children }) => (
12 <QueryClientProvider client={queryClient}>
13 {children}
14 </QueryClientProvider>
15 )
16 }
17
18 test("my first test", async () => {
19 const { result } = renderHook(() => useCustomHook(), {
20 wrapper: createWrapper()
21 })
22 }
This 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.
setQueryDefaults
The best advice I can give you for this problem is: Don't set these options on useQuery directly. Try to
use and override the defaults as much as possible, and if you really need to change something for specific
queries, use queryClient.setQueryDefaults.
So for example, instead of setting retry on useQuery :
not-on-useQuery
TSX Copy
1 const queryClient = new QueryClient()
2
3 function App() {
4 return (
5 <QueryClientProvider client={queryClient}>
6 <Example />
7 </QueryClientProvider>
8 )
9 }
10
11 function Example() {
12 // 🚨
you cannot override this setting for tests!
13 const queryInfo = useQuery({
14 queryKey: ['todos'],
15 queryFn: fetchTodos,
16 retry: 5,
17 })
18 }
Here, all queries will retry two times, only todos will retry five times, and I still have the option to turn it off
for all queries in my tests 🙌 .
ReactQueryConfigProvider
Of course, this only works for known query keys. Sometimes, you really want to set some configs on a
subset of your component tree. In v2, React Query had a ReactQueryConfigProvider for that exact use-
case. You can achieve the same thing in v3 with a couple of lines of codes:
ReactQueryConfigProvider
JSX Copy
1 const ReactQueryConfigProvider = ({ children, defaultOptions }) => {
2 const client = useQueryClient()
3 const [newClient] = React.useState(
4 () =>
5 new QueryClient({
6 queryCache: client.getQueryCache(),
7 muationCache: client.getMutationCache(),
8 defaultOptions,
9 })
10 )
11
12 return (
13 <QueryClientProvider client={newClient}>
14 {children}
15 </QueryClientProvider>
16 )
17 }
Update
@testing-library/react v13.1.0 also has a new renderHook that you can use. However, it doesn't return
its own waitFor util, so you'll have to use the one you can import from @testing-library/react
instead. The API is a bit different, as it doesn't allow to return a boolean , but expects a Promise
instead. That means we must adapt our code slightly:
new-render-hook
TSX Copy
1 import { waitFor, renderHook } from '@testing-library/react'
2
3 test("my first test", async () => {
4 const { result } = renderHook(() => useCustomHook(), {
5 wrapper: createWrapper()
6 })
7
8 // ✅
return a Promise via expect to waitFor
9 await waitFor(() => expect(result.current.isSuccess).toBe(true))
10
11 expect(result.current.data).toBeDefined()
12 }