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

devtools.test.tsx

612 lines16.6 KB

1import React from 'react'
2​
3import { fireEvent, screen, waitFor, act } from '@testing-library/react'
4import { ErrorBoundary } from 'react-error-boundary'
5​
6import '@testing-library/jest-dom'
7import { useQuery, QueryClient } from '../..'
8import {
9 getByTextContent,
10 renderWithClient,
11 sleep,
12 createQueryClient,
13} from './utils'
14​
15Object.defineProperty(window, 'matchMedia', {
16 writable: true,
17 value: jest.fn().mockImplementation((query: string) => ({
18 matches: false,
19 media: query,
20 onchange: null,
21 addListener: jest.fn(), // deprecated
22 removeListener: jest.fn(), // deprecated
23 addEventListener: jest.fn(),
24 removeEventListener: jest.fn(),
25 dispatchEvent: jest.fn(),
26 })),
27})
28​
29describe('ReactQueryDevtools', () => {
30 beforeEach(() => {
31 localStorage.removeItem('reactQueryDevtoolsOpen')
32 })
33 it('should be able to open and close devtools', async () => {
34 const { queryClient } = createQueryClient()
35 const onCloseClick = jest.fn()
36 const onToggleClick = jest.fn()
37​
38 function Page() {
39 const { data = 'default' } = useQuery(['check'], async () => {
40 await sleep(10)
41 return 'test'
42 })
43​
44 return (
45 <div>
46 <h1>{data}</h1>
47 </div>
48 )
49 }
50​
51 renderWithClient(queryClient, <Page />, {
52 initialIsOpen: false,
53 closeButtonProps: { onClick: onCloseClick },
54 toggleButtonProps: { onClick: onToggleClick },
55 })
56​
57 const closeButton = screen.queryByRole('button', {
58 name: /close react query devtools/i,
59 })
60 expect(closeButton).toBeNull()
61 fireEvent.click(
62 screen.getByRole('button', { name: /open react query devtools/i })
63 )
64​
65 expect(onToggleClick).toHaveBeenCalledTimes(1)
66​
67 fireEvent.click(
68 screen.getByRole('button', { name: /close react query devtools/i })
69 )
70​
71 await screen.findByRole('button', { name: /open react query devtools/i })
72​
73 expect(onCloseClick).toHaveBeenCalledTimes(1)
74 })
75​
76 it('should be able to drag devtools without error', async () => {
77 const { queryClient } = createQueryClient()
78​
79 function Page() {
80 const { data = 'default' } = useQuery(['check'], async () => {
81 await sleep(10)
82 return 'test'
83 })
84​
85 return (
86 <div>
87 <h1>{data}</h1>
88 </div>
89 )
90 }
91​
92 const result = renderWithClient(queryClient, <Page />, {
93 initialIsOpen: false,
94 })
95​
96 const draggableElement = result.container
97 .querySelector('#ReactQueryDevtoolsPanel')
98 ?.querySelector('div')
99​
100 if (!draggableElement) {
101 throw new Error('Could not find the draggable element')
102 }
103​
104 await act(async () => {
105 fireEvent.mouseDown(draggableElement)
106 })
107 })
108​
109 it('should display the correct query states', async () => {
110 const { queryClient, queryCache } = createQueryClient()
111​
112 function Page() {
113 const { data = 'default' } = useQuery(
114 ['check'],
115 async () => {
116 await sleep(100)
117 return 'test'
118 },
119 { staleTime: 300 }
120 )
121​
122 return (
123 <div>
124 <h1>{data}</h1>
125 </div>
126 )
127 }
128​
129 function PageParent() {
130 const [isPageVisible, togglePageVisible] = React.useReducer(
131 visible => !visible,
132 true
133 )
134​
135 return (
136 <div>
137 <button
138 type="button"
139 aria-label="Toggle page visibility"
140 onClick={togglePageVisible}
141 >
142 Toggle Page
143 </button>
144 {isPageVisible && <Page />}
145 </div>
146 )
147 }
148​
149 renderWithClient(queryClient, <PageParent />)
150​
151 fireEvent.click(
152 screen.getByRole('button', { name: /open react query devtools/i })
153 )
154​
155 const currentQuery = queryCache.find(['check'])
156​
157 // When the query is fetching then expect number of
158 // fetching queries to be 1
159 expect(currentQuery?.state.fetchStatus).toEqual('fetching')
160 await screen.findByText(
161 getByTextContent(
162 'fresh (0) fetching (1) paused (0) stale (0) inactive (0)'
163 )
164 )
165​
166 // When we are done fetching the query doesn't go stale
167 // until 300ms after, so expect the number of fresh
168 // queries to be 1
169 await waitFor(() => {
170 expect(currentQuery?.state.fetchStatus).toEqual('idle')
171 })
172 await screen.findByText(
173 getByTextContent(
174 'fresh (1) fetching (0) paused (0) stale (0) inactive (0)'
175 )
176 )
177​
178 // Then wait for the query to go stale and then
179 // expect the number of stale queries to be 1
180 await waitFor(() => {
181 expect(currentQuery?.isStale()).toEqual(false)
182 })
183 await screen.findByText(
184 getByTextContent(
185 'fresh (0) fetching (0) paused (0) stale (1) inactive (0)'
186 )
187 )
188​
189 // Unmount the page component thus making the query inactive
190 // and expect number of inactive queries to be 1
191 fireEvent.click(
192 screen.getByRole('button', { name: /toggle page visibility/i })
193 )
194 await screen.findByText(
195 getByTextContent(
196 'fresh (0) fetching (0) paused (0) stale (0) inactive (1)'
197 )
198 )
199 })
200​
201 it('should display the query hash and open the query details', async () => {
202 const { queryClient, queryCache } = createQueryClient()
203​
204 function Page() {
205 const { data = 'default' } = useQuery(['check'], async () => {
206 await sleep(10)
207 return 'test'
208 })
209​
210 return (
211 <div>
212 <h1>{data}</h1>
213 </div>
214 )
215 }
216​
217 renderWithClient(queryClient, <Page />)
218​
219 fireEvent.click(
220 screen.getByRole('button', { name: /open react query devtools/i })
221 )
222​
223 const currentQuery = queryCache.find(['check'])
224​
225 await screen.findByText(getByTextContent(`1${currentQuery?.queryHash}`))
226​
227 const queryButton = await screen.findByRole('button', {
228 name: `Open query details for ${currentQuery?.queryHash}`,
229 })
230​
231 fireEvent.click(queryButton)
232​
233 await screen.findByText(/query details/i)
234 })
235​
236 it('should filter the queries via the query hash', async () => {
237 const { queryClient, queryCache } = createQueryClient()
238​
239 function Page() {
240 const fooResult = useQuery(['foo'], async () => {
241 await sleep(10)
242 return 'foo-result'
243 })
244​
245 const barResult = useQuery(['bar'], async () => {
246 await sleep(10)
247 return 'bar-result'
248 })
249​
250 const bazResult = useQuery(['baz'], async () => {
251 await sleep(10)
252 return 'baz-result'
253 })
254​
255 return (
256 <div>
257 <h1>
258 {barResult.data} {fooResult.data} {bazResult.data}
259 </h1>
260 </div>
261 )
262 }
263​
264 renderWithClient(queryClient, <Page />)
265​
266 fireEvent.click(
267 screen.getByRole('button', { name: /open react query devtools/i })
268 )
269​
270 const fooQueryHash = queryCache.find(['foo'])?.queryHash ?? 'invalid hash'
271 const barQueryHash = queryCache.find(['bar'])?.queryHash ?? 'invalid hash'
272 const bazQueryHash = queryCache.find(['baz'])?.queryHash ?? 'invalid hash'
273​
274 await screen.findByText(fooQueryHash)
275 screen.getByText(barQueryHash)
276 screen.getByText(bazQueryHash)
277​
278 const filterInput = screen.getByLabelText(/filter by queryhash/i)
279 fireEvent.change(filterInput, { target: { value: 'fo' } })
280​
281 await screen.findByText(fooQueryHash)
282 const barItem = screen.queryByText(barQueryHash)
283 const bazItem = screen.queryByText(bazQueryHash)
284 expect(barItem).toBeNull()
285 expect(bazItem).toBeNull()
286​
287 fireEvent.change(filterInput, { target: { value: '' } })
288 })
289​
290 it('should show a disabled label if all observers are disabled', async () => {
291 const { queryClient } = createQueryClient()
292​
293 function Page() {
294 const [enabled, setEnabled] = React.useState(false)
295 const { data } = useQuery(
296 ['key'],
297 async () => {
298 await sleep(10)
299 return 'test'
300 },
301 {
302 enabled,
303 }
304 )
305​
306 return (
307 <div>
308 <h1>{data}</h1>
309 <button onClick={() => setEnabled(true)}>Enable Query</button>
310 </div>
311 )
312 }
313​
314 renderWithClient(queryClient, <Page />, { initialIsOpen: true })
315​
316 await screen.findByText(/disabled/i)
317​
318 fireEvent.click(screen.getByRole('button', { name: /enable query/i }))
319​
320 await waitFor(() => {
321 expect(screen.queryByText(/disabled/i)).not.toBeInTheDocument()
322 })
323 })
324​
325 it('should not show a disabled label for inactive queries', async () => {
326 const { queryClient } = createQueryClient()
327​
328 function Page() {
329 const { data } = useQuery(['key'], () => Promise.resolve('test'), {
330 enabled: false,
331 })
332​
333 return (
334 <div>
335 <h1>{data}</h1>
336 </div>
337 )
338 }
339​
340 function App() {
341 const [visible, setVisible] = React.useState(true)
342​
343 return (
344 <div>
345 {visible ? <Page /> : null}
346 <button onClick={() => setVisible(false)}>Hide Query</button>
347 </div>
348 )
349 }
350​
351 renderWithClient(queryClient, <App />, { initialIsOpen: true })
352​
353 await screen.findByText(/disabled/i)
354​
355 fireEvent.click(screen.getByRole('button', { name: /hide query/i }))
356​
357 await waitFor(() => {
358 expect(screen.queryByText(/disabled/i)).not.toBeInTheDocument()
359 })
360 })
361​
362 it('should simulate offline mode', async () => {
363 const { queryClient } = createQueryClient()
364 let count = 0
365​
366 function App() {
367 const { data, fetchStatus } = useQuery(['key'], () => {
368 count++
369 return Promise.resolve('test')
370 })
371​
372 return (
373 <div>
374 <h1>
375 {data}, {fetchStatus}
376 </h1>
377 </div>
378 )
379 }
380​
381 renderWithClient(queryClient, <App />, {
382 initialIsOpen: true,
383 })
384​
385 await screen.findByRole('heading', { name: /test/i })
386​
387 fireEvent.click(
388 screen.getByRole('button', { name: /mock offline behavior/i })
389 )
390​
391 const queryButton = await screen.findByRole('button', {
392 name: 'Open query details for ["key"]',
393 })
394 fireEvent.click(queryButton)
395​
396 const refetchButton = await screen.findByRole('button', {
397 name: /refetch/i,
398 })
399 fireEvent.click(refetchButton)
400​
401 await waitFor(() => {
402 expect(screen.getByText('test, paused')).toBeInTheDocument()
403 })
404​
405 fireEvent.click(
406 screen.getByRole('button', { name: /restore offline mock/i })
407 )
408​
409 await waitFor(() => {
410 expect(screen.getByText('test, idle')).toBeInTheDocument()
411 })
412​
413 expect(count).toBe(2)
414 })
415​
416 it('should sort the queries according to the sorting filter', async () => {
417 const { queryClient, queryCache } = createQueryClient()
418​
419 function Page() {
420 const query1Result = useQuery(['query-1'], async () => {
421 await sleep(20)
422 return 'query-1-result'
423 })
424​
425 const query3Result = useQuery(
426 ['query-3'],
427 async () => {
428 await sleep(10)
429 return 'query-3-result'
430 },
431 { staleTime: Infinity, enabled: typeof query1Result.data === 'string' }
432 )
433​
434 const query2Result = useQuery(
435 ['query-2'],
436 async () => {
437 await sleep(10)
438 return 'query-2-result'
439 },
440 {
441 enabled: typeof query3Result.data === 'string',
442 }
443 )
444​
445 return (
446 <div>
447 <h1>
448 {query1Result.data} {query2Result.data} {query3Result.data}
449 </h1>
450 </div>
451 )
452 }
453​
454 renderWithClient(queryClient, <Page />)
455​
456 fireEvent.click(
457 screen.getByRole('button', { name: /open react query devtools/i })
458 )
459​
460 const query1Hash = queryCache.find(['query-1'])?.queryHash ?? 'invalid hash'
461 const query2Hash = queryCache.find(['query-2'])?.queryHash ?? 'invalid hash'
462 const query3Hash = queryCache.find(['query-3'])?.queryHash ?? 'invalid hash'
463​
464 const sortSelect = screen.getByLabelText(/sort queries/i)
465 let queries = []
466​
467 // When sorted by query hash the queries get sorted according
468 // to just the number, with the order being -> query-1, query-2, query-3
469 fireEvent.change(sortSelect, { target: { value: 'Query Hash' } })
470​
471 /** To check the order of the queries we can use regex to find
472 * all the row items in an array and then compare the items
473 * one by one in the order we expect it
474 * @reference https://github.com/testing-library/react-testing-library/issues/313#issuecomment-625294327
475 */
476 queries = await screen.findAllByText(/\["query-[1-3]"\]/)
477 expect(queries[0]?.textContent).toEqual(query1Hash)
478 expect(queries[1]?.textContent).toEqual(query2Hash)
479 expect(queries[2]?.textContent).toEqual(query3Hash)
480​
481 // Wait for the queries to be resolved
482 await screen.findByText(/query-1-result query-2-result query-3-result/i)
483​
484 // When sorted by the last updated date the queries are sorted by the time
485 // they were updated and since the query-2 takes longest time to complete
486 // and query-1 the shortest, so the order is -> query-2, query-3, query-1
487 fireEvent.change(sortSelect, { target: { value: 'Last Updated' } })
488​
489 queries = await screen.findAllByText(/\["query-[1-3]"\]/)
490 expect(queries[0]?.textContent).toEqual(query2Hash)
491 expect(queries[1]?.textContent).toEqual(query3Hash)
492 expect(queries[2]?.textContent).toEqual(query1Hash)
493​
494 // When sorted by the status and then last updated date the queries
495 // query-3 takes precedence because its stale time being infinity, it
496 // always remains fresh, the rest of the queries are sorted by their last
497 // updated time, so the resulting order is -> query-3, query-2, query-1
498 fireEvent.change(sortSelect, {
499 target: { value: 'Status > Last Updated' },
500 })
501​
502 queries = await screen.findAllByText(/\["query-[1-3]"\]/)
503 expect(queries[0]?.textContent).toEqual(query3Hash)
504 expect(queries[1]?.textContent).toEqual(query2Hash)
505 expect(queries[2]?.textContent).toEqual(query1Hash)
506​
507 // Switch the order form ascending to descending and expect the
508 // query order to be reversed from previous state
509 fireEvent.click(screen.getByRole('button', { name: /⬆ asc/i }))
510​
511 queries = await screen.findAllByText(/\["query-[1-3]"\]/)
512 expect(queries[0]?.textContent).toEqual(query1Hash)
513 expect(queries[1]?.textContent).toEqual(query2Hash)
514 expect(queries[2]?.textContent).toEqual(query3Hash)
515 })
516​
517 describe('with custom context', () => {
518 it('should render without error when the custom context aligns', async () => {
519 const context = React.createContext<QueryClient | undefined>(undefined)
520 const { queryClient } = createQueryClient()
521​
522 function Page() {
523 const { data = 'default' } = useQuery(['check'], async () => 'test', {
524 context,
525 })
526​
527 return (
528 <div>
529 <h1>{data}</h1>
530 </div>
531 )
532 }
533​
534 renderWithClient(queryClient, <Page />, {
535 initialIsOpen: false,
536 context,
537 })
538​
539 await screen.findByRole('button', { name: /open react query devtools/i })
540 })
541​
542 it('should render with error when the custom context is not passed to useQuery', async () => {
543 const consoleErrorMock = jest.spyOn(console, 'error')
544 consoleErrorMock.mockImplementation(() => undefined)
545​
546 const context = React.createContext<QueryClient | undefined>(undefined)
547 const { queryClient } = createQueryClient()
548​
549 function Page() {
550 const { data = 'default' } = useQuery(['check'], async () => 'test', {
551 useErrorBoundary: true,
552 })
553​
554 return (
555 <div>
556 <h1>{data}</h1>
557 </div>
558 )
559 }
560​
561 const rendered = renderWithClient(
562 queryClient,
563 <ErrorBoundary fallbackRender={() => <div>error boundary</div>}>
564 <Page />
565 </ErrorBoundary>,
566 {
567 initialIsOpen: false,
568 context,
569 }
570 )
571​
572 await waitFor(() => rendered.getByText('error boundary'))
573​
574 consoleErrorMock.mockRestore()
575 })
576​
577 it('should render with error when the custom context is not passed to ReactQueryDevtools', async () => {
578 const consoleErrorMock = jest.spyOn(console, 'error')
579 consoleErrorMock.mockImplementation(() => undefined)
580​
581 const context = React.createContext<QueryClient | undefined>(undefined)
582 const { queryClient } = createQueryClient()
583​
584 function Page() {
585 const { data = 'default' } = useQuery(['check'], async () => 'test', {
586 useErrorBoundary: true,
587 context,
588 })
589​
590 return (
591 <div>
592 <h1>{data}</h1>
593 </div>
594 )
595 }
596​
597 const rendered = renderWithClient(
598 queryClient,
599 <ErrorBoundary fallbackRender={() => <div>error boundary</div>}>
600 <Page />
601 </ErrorBoundary>,
602 {
603 initialIsOpen: false,
604 }
605 )
606​
607 await waitFor(() => rendered.getByText('error boundary'))
608​
609 consoleErrorMock.mockRestore()
610 })
611 })
612})