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

devtools.test.tsx

766 lines20.9 KB

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