Open History to see the last commit
1// @vitest-environment jsdom
2import { describe, expect, it, vi } from 'vitest'
3import { fireEvent, render } from '@testing-library/react'
4import * as React from 'react'
5import { ErrorBoundary } from 'react-error-boundary'
6import { queryKey } from '@tanstack/query-test-utils'
7import {
8 QueryClient,
9 QueryClientProvider,
10 QueryErrorResetBoundary,
11 useQuery,
12} from '..'
13β
14describe('issue 9728', () => {
15 it('should refetch after error when staleTime is Infinity and previous data exists', async () => {
16 const key = queryKey()
17 const queryFn = vi.fn()
18 let count = 0
19β
20 queryFn.mockImplementation(async () => {
21 count++
22 if (count === 2) {
23 throw new Error('Error ' + count)
24 }
25 return 'Success ' + count
26 })
27β
28 const queryClient = new QueryClient({
29 defaultOptions: {
30 queries: {
31 retry: false,
32 staleTime: Infinity,
33 },
34 },
35 })
36β
37 function Page() {
38 const [_, forceUpdate] = React.useState(0)
39β
40 React.useEffect(() => {
41 forceUpdate(1)
42 }, [])
43β
44 const { data, refetch } = useQuery({
45 queryKey: key,
46 queryFn,
47 throwOnError: true,
48 })
49β
50 return (
51 <div>
52 <div>Data: {data}</div>
53 <button onClick={() => refetch()}>Refetch</button>
54 </div>
55 )
56 }
57β
58 function App() {
59 return (
60 <QueryErrorResetBoundary>
61 {({ reset }) => (
62 <ErrorBoundary
63 onReset={reset}
64 fallbackRender={({ resetErrorBoundary }) => (
65 <div>
66 <div>Status: error</div>
67 <button onClick={resetErrorBoundary}>Retry</button>
68 </div>
69 )}
70 >
71 <React.Suspense fallback={<div>Loading...</div>}>
72 <Page />
73 </React.Suspense>
74 </ErrorBoundary>
75 )}
76 </QueryErrorResetBoundary>
77 )
78 }
79β
80 const { getByText, findByText } = render(
81 <React.StrictMode>
82 <QueryClientProvider client={queryClient}>
83 <App />
84 </QueryClientProvider>
85 </React.StrictMode>,
86 )
87β
88 // 1. First mount -> Success
89 await findByText('Data: Success 1')
90 expect(queryFn).toHaveBeenCalledTimes(1)
91β
92 // 2. Click Refetch -> Triggers fetch -> Fails (Error 2) -> ErrorBoundary
93 fireEvent.click(getByText('Refetch'))
94β
95 // Wait for error UI
96 await findByText('Status: error')
97 expect(queryFn).toHaveBeenCalledTimes(2)
98β
99 // 3. Click Retry -> Remounts
100 // Because staleTime is Infinity and we have Data from (1),
101 // AND we are in Error state.
102 fireEvent.click(getByText('Retry'))
103β
104 // Should call queryFn again (3rd time) and succeed
105 await findByText('Data: Success 3')
106 expect(queryFn).toHaveBeenCalledTimes(3)
107 })
108})