-
Previously in version 1 and 2 of React Query we had this in our Jest setup import { queryCache } from "react-query"
afterEach(() => queryCache.clear()) this way each test run would run with a fresh empty cache, no matter how deeply nested the tests got. However, with version 3 we can't import the query cache anymore as its part of the context that is run within our tests. We currently are wrapping our contexts that are used in our apps with the React Testing Library wrapper, so we have access to the query client and it's config in our tests. Therefore, I have come up with this solution to get our tests passing again import { queryClient } from "app/context"
afterEach(() => queryClient.clear()) This however means we now need to export the import { QueryClient, QueryClientProvider } from "react-query"
export const queryClient = new QueryClient({
defaultOptions: {
queries: {
refetchOnWindowFocus: false,
},
},
})
export function AppProviders({ children }) {
return (
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
)
} I'm not super keen on exporting the Is there a better way to clear the cache after every test in Jest in version 3, or this an alright solution? |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 5 replies
-
I hear you on exporting things only for testing purposes isn't great, but there are first-class apis, like the hydration api which don't require being called from the context of React and take the So I think your solution is probably fine, and will cover more cases later on. |
Beta Was this translation helpful? Give feedback.
-
Alternatively, you can create a separate query client for testing. This might be good to turn off certain settings for tests only, like retries. |
Beta Was this translation helpful? Give feedback.
-
For anyone that just wants straight up code, here is my
in my test files I can |
Beta Was this translation helpful? Give feedback.
Alternatively, you can create a separate query client for testing. This might be good to turn off certain settings for tests only, like retries.