Open History to see the last commit
1import * as React from 'react'
2import { act, fireEvent, screen, waitFor } from '@testing-library/react'
3import { ErrorBoundary } from 'react-error-boundary'
4import '@testing-library/jest-dom'
5import { useQuery } from '@tanstack/react-query'
6import UserEvent from '@testing-library/user-event'
7import { defaultPanelSize, sortFns } from '../utils'
8import {
9 createQueryClient,
10 getByTextContent,
11 renderWithClient,
12 sleep,
13} from './utils'
14import type { QueryClient } from '@tanstack/react-query'
15β
16// TODO: This should be removed with the types for react-error-boundary get updated.
17declare module 'react-error-boundary' {
18 interface ErrorBoundaryPropsWithFallback {
19 children: any
20 }
21}
22β
23class CustomError extends Error {
24 constructor(message: string) {
25 super(message)
26 this.name = 'CustomError'
27 }
28}
29β
30Object.defineProperty(window, 'matchMedia', {
31 writable: true,
32 value: jest.fn().mockImplementation((query: string) => ({
33 matches: false,
34 media: query,
35 onchange: null,
36 addListener: jest.fn(), // deprecated
37 removeListener: jest.fn(), // deprecated
38 addEventListener: jest.fn(),
39 removeEventListener: jest.fn(),
40 dispatchEvent: jest.fn(),
41 })),
42})
43β
44describe('ReactQueryDevtools', () => {
45 beforeEach(() => {
46 localStorage.removeItem('reactQueryDevtoolsOpen')
47 localStorage.removeItem('reactQueryDevtoolsPanelPosition')
48 })
49 it('should be able to open and close devtools', async () => {
50 const { queryClient } = createQueryClient()
51 const onCloseClick = jest.fn()
52 const onToggleClick = jest.fn()
53β
54 function Page() {
55 const { data = 'default' } = useQuery(['check'], async () => {
56 await sleep(10)
57 return 'test'
58 })
59β
60 return (
61 <div>
62 <h1>{data}</h1>
63 </div>
64 )
65 }
66β
67 renderWithClient(queryClient, <Page />, {
68 initialIsOpen: false,
69 closeButtonProps: { onClick: onCloseClick },
70 toggleButtonProps: { onClick: onToggleClick },
71 })
72β
73 const verifyDevtoolsIsOpen = () => {
74 expect(
75 screen.queryByRole('generic', { name: /react query devtools panel/i }),
76 ).not.toBeNull()
77 expect(
78 screen.queryByRole('button', { name: /open react query devtools/i }),
79 ).toBeNull()
80 }
81 const verifyDevtoolsIsClosed = () => {
82 expect(
83 screen.queryByRole('generic', { name: /react query devtools panel/i }),
84 ).toBeNull()
85 expect(
86 screen.queryByRole('button', { name: /open react query devtools/i }),
87 ).not.toBeNull()
88 }
89β
90 const waitForDevtoolsToOpen = () =>
91 screen.findByRole('button', { name: /close react query devtools/i })
92 const waitForDevtoolsToClose = () =>
93 screen.findByRole('button', { name: /open react query devtools/i })
94β
95 const getOpenLogoButton = () =>
96 screen.getByRole('button', { name: /open react query devtools/i })
97 const getCloseLogoButton = () =>
98 screen.getByRole('button', { name: /close react query devtools/i })
99 const getCloseButton = () =>
100 screen.getByRole('button', { name: /^close$/i })
101β
102 verifyDevtoolsIsClosed()
103β
104 fireEvent.click(getOpenLogoButton())
105 await waitForDevtoolsToOpen()
106β
107 verifyDevtoolsIsOpen()
108β
109 fireEvent.click(getCloseLogoButton())
110 await waitForDevtoolsToClose()
111β
112 verifyDevtoolsIsClosed()
113β
114 fireEvent.click(getOpenLogoButton())
115 await waitForDevtoolsToOpen()
116β
117 verifyDevtoolsIsOpen()
118β
119 fireEvent.click(getCloseButton())
120 await waitForDevtoolsToClose()
121β
122 verifyDevtoolsIsClosed()
123 })
124β
125 it('should be able to drag devtools without error', async () => {
126 const { queryClient } = createQueryClient()
127β
128 function Page() {
129 const { data = 'default' } = useQuery(['check'], async () => {
130 await sleep(10)
131 return 'test'
132 })
133β
134 return (
135 <div>
136 <h1>{data}</h1>
137 </div>
138 )
139 }
140β
141 const result = renderWithClient(queryClient, <Page />, {
142 initialIsOpen: false,
143 })
144β
145 const draggableElement = result.container
146 .querySelector('#ReactQueryDevtoolsPanel')
147 ?.querySelector('div')
148β
149 if (!draggableElement) {
150 throw new Error('Could not find the draggable element')
151 }
152β
153 await act(async () => {
154 fireEvent.mouseDown(draggableElement)
155 })
156 })
157β
158 it('should display the correct query states', async () => {
159 const { queryClient, queryCache } = createQueryClient()
160β
161 function Page() {
162 const { data = 'default' } = useQuery(
163 ['check'],
164 async () => {
165 await sleep(100)
166 return 'test'
167 },
168 { staleTime: 300 },
169 )
170β
171 return (
172 <div>
173 <h1>{data}</h1>
174 </div>
175 )
176 }
177β
178 function PageParent() {
179 const [isPageVisible, togglePageVisible] = React.useReducer(
180 (visible) => !visible,
181 true,
182 )
183β
184 return (
185 <div>
186 <button
187 type="button"
188 aria-label="Toggle page visibility"
189 onClick={togglePageVisible}
190 >
191 Toggle Page
192 </button>
193 {isPageVisible && <Page />}
194 </div>
195 )
196 }
197β
198 renderWithClient(queryClient, <PageParent />)
199β
200 fireEvent.click(
201 screen.getByRole('button', { name: /open react query devtools/i }),
202 )
203β
204 const currentQuery = queryCache.find(['check'])
205β
206 // When the query is fetching then expect number of
207 // fetching queries to be 1
208 expect(currentQuery?.state.fetchStatus).toEqual('fetching')
209 await screen.findByText(
210 getByTextContent(
211 'fresh (0) fetching (1) paused (0) stale (0) inactive (0)',
212 ),
213 )
214β
215 // When we are done fetching the query doesn't go stale
216 // until 300ms after, so expect the number of fresh
217 // queries to be 1
218 await waitFor(() => {
219 expect(currentQuery?.state.fetchStatus).toEqual('idle')
220 })
221 await screen.findByText(
222 getByTextContent(
223 'fresh (1) fetching (0) paused (0) stale (0) inactive (0)',
224 ),
225 )
226β
227 // Then wait for the query to go stale and then
228 // expect the number of stale queries to be 1
229 await waitFor(() => {
230 expect(currentQuery?.isStale()).toEqual(false)
231 })
232 await screen.findByText(
233 getByTextContent(
234 'fresh (0) fetching (0) paused (0) stale (1) inactive (0)',
235 ),
236 )
237β
238 // Unmount the page component thus making the query inactive
239 // and expect number of inactive queries to be 1
240 fireEvent.click(
241 screen.getByRole('button', { name: /toggle page visibility/i }),
242 )
243 await screen.findByText(
244 getByTextContent(
245 'fresh (0) fetching (0) paused (0) stale (0) inactive (1)',
246 ),
247 )
248 })
249β
250 it('should display the query hash and open the query details', async () => {
251 const { queryClient, queryCache } = createQueryClient()
252β
253 function Page() {
254 const { data = 'default' } = useQuery(['check'], async () => {
255 await sleep(10)
256 return 'test'
257 })
258β
259 return (
260 <div>
261 <h1>{data}</h1>
262 </div>
263 )
264 }
265β
266 renderWithClient(queryClient, <Page />)
267β
268 fireEvent.click(
269 screen.getByRole('button', { name: /open react query devtools/i }),
270 )
271β
272 const currentQuery = queryCache.find(['check'])
273β
274 await screen.findByText(getByTextContent(`1${currentQuery?.queryHash}`))
275β
276 const queryButton = await screen.findByRole('button', {
277 name: `Open query details for ${currentQuery?.queryHash}`,
278 })
279β
280 fireEvent.click(queryButton)
281β
282 await screen.findByText(/query details/i)
283 })
284β
285 it('should filter the queries via the query hash', async () => {
286 const { queryClient, queryCache } = createQueryClient()
287β
288 function Page() {
289 const fooResult = useQuery(['foo'], async () => {
290 await sleep(10)
291 return 'foo-result'
292 })
293β
294 const barResult = useQuery(['bar'], async () => {
295 await sleep(10)
296 return 'bar-result'
297 })
298β
299 const bazResult = useQuery(['baz'], async () => {
300 await sleep(10)
301 return 'baz-result'
302 })
303β
304 return (
305 <div>
306 <h1>
307 {barResult.data} {fooResult.data} {bazResult.data}
308 </h1>
309 </div>
310 )
311 }
312β
313 renderWithClient(queryClient, <Page />)
314β
315 fireEvent.click(
316 screen.getByRole('button', { name: /open react query devtools/i }),
317 )
318β
319 const fooQueryHash = queryCache.find(['foo'])?.queryHash ?? 'invalid hash'
320 const barQueryHash = queryCache.find(['bar'])?.queryHash ?? 'invalid hash'
321 const bazQueryHash = queryCache.find(['baz'])?.queryHash ?? 'invalid hash'
322β
323 await screen.findByText(fooQueryHash)
324 screen.getByText(barQueryHash)
325 screen.getByText(bazQueryHash)
326β
327 const filterInput = screen.getByLabelText(/filter by queryhash/i)
328 fireEvent.change(filterInput, { target: { value: 'fo' } })
329β
330 await screen.findByText(fooQueryHash)
331 const barItem = screen.queryByText(barQueryHash)
332 const bazItem = screen.queryByText(bazQueryHash)
333 expect(barItem).toBeNull()
334 expect(bazItem).toBeNull()
335β
336 fireEvent.change(filterInput, { target: { value: '' } })
337 })
338β
339 it('should show a disabled label if all observers are disabled', async () => {
340 const { queryClient } = createQueryClient()
341β
342 function Page() {
343 const [enabled, setEnabled] = React.useState(false)
344 const { data } = useQuery(
345 ['key'],
346 async () => {
347 await sleep(10)
348 return 'test'
349 },
350 {
351 enabled,
352 },
353 )
354β
355 return (
356 <div>
357 <h1>{data}</h1>
358 <button onClick={() => setEnabled(true)}>Enable Query</button>
359 </div>
360 )
361 }
362β
363 renderWithClient(queryClient, <Page />, { initialIsOpen: true })
364β
365 await screen.findByText(/disabled/i)
366β
367 fireEvent.click(screen.getByRole('button', { name: /enable query/i }))
368β
369 await waitFor(() => {
370 expect(screen.queryByText(/disabled/i)).not.toBeInTheDocument()
371 })
372 })
373β
374 it('should not show a disabled label for inactive queries', async () => {
375 const { queryClient } = createQueryClient()
376β
377 function Page() {
378 const { data } = useQuery(['key'], () => Promise.resolve('test'), {
379 enabled: false,
380 })
381β
382 return (
383 <div>
384 <h1>{data}</h1>
385 </div>
386 )
387 }
388β
389 function App() {
390 const [visible, setVisible] = React.useState(true)
391β
392 return (
393 <div>
394 {visible ? <Page /> : null}
395 <button onClick={() => setVisible(false)}>Hide Query</button>
396 </div>
397 )
398 }
399β
400 renderWithClient(queryClient, <App />, { initialIsOpen: true })
401β
402 await screen.findByText(/disabled/i)
403β
404 fireEvent.click(screen.getByRole('button', { name: /hide query/i }))
405β
406 await waitFor(() => {
407 expect(screen.queryByText(/disabled/i)).not.toBeInTheDocument()
408 })
409 })
410β
411 it('should simulate offline mode', async () => {
412 const { queryClient } = createQueryClient()
413 let count = 0
414β
415 function App() {
416 const { data, fetchStatus } = useQuery(['key'], () => {
417 count++
418 return Promise.resolve('test')
419 })
420β
421 return (
422 <div>
423 <h1>
424 {data}, {fetchStatus}
425 </h1>
426 </div>
427 )
428 }
429β
430 renderWithClient(queryClient, <App />, {
431 initialIsOpen: true,
432 })
433β
434 await screen.findByRole('heading', { name: /test/i })
435β
436 fireEvent.click(
437 screen.getByRole('button', { name: /mock offline behavior/i }),
438 )
439β
440 const queryButton = await screen.findByRole('button', {
441 name: 'Open query details for ["key"]',
442 })
443 fireEvent.click(queryButton)
444β
445 const refetchButton = await screen.findByRole('button', {
446 name: /refetch/i,
447 })
448 fireEvent.click(refetchButton)
449β
450 await waitFor(() => {
451 expect(screen.getByText('test, paused')).toBeInTheDocument()
452 })
453β
454 fireEvent.click(
455 screen.getByRole('button', { name: /restore offline mock/i }),
456 )
457β
458 await waitFor(() => {
459 expect(screen.getByText('test, idle')).toBeInTheDocument()
460 })
461β
462 expect(count).toBe(2)
463 })
464β
465 it('should sort the queries according to the sorting filter', async () => {
466 const { queryClient, queryCache } = createQueryClient()
467β
468 function Page() {
469 const query1Result = useQuery(['query-1'], async () => {
470 await sleep(20)
471 return 'query-1-result'
472 })
473β
474 const query3Result = useQuery(
475 ['query-3'],
476 async () => {
477 await sleep(10)
478 return 'query-3-result'
479 },
480 { staleTime: Infinity, enabled: typeof query1Result.data === 'string' },
481 )
482β
483 const query2Result = useQuery(
484 ['query-2'],
485 async () => {
486 await sleep(10)
487 return 'query-2-result'
488 },
489 {
490 enabled: typeof query3Result.data === 'string',
491 },
492 )
493β
494 return (
495 <div>
496 <h1>
497 {query1Result.data} {query2Result.data} {query3Result.data}
498 </h1>
499 </div>
500 )
501 }
502β
503 renderWithClient(queryClient, <Page />)
504β
505 fireEvent.click(
506 screen.getByRole('button', { name: /open react query devtools/i }),
507 )
508β
509 const query1Hash = queryCache.find(['query-1'])?.queryHash ?? 'invalid hash'
510 const query2Hash = queryCache.find(['query-2'])?.queryHash ?? 'invalid hash'
511 const query3Hash = queryCache.find(['query-3'])?.queryHash ?? 'invalid hash'
512β
513 const sortSelect = screen.getByLabelText(/sort queries/i)
514 let queries = []
515β
516 // When sorted by query hash the queries get sorted according
517 // to just the number, with the order being -> query-1, query-2, query-3
518 fireEvent.change(sortSelect, { target: { value: 'Query Hash' } })
519β
520 /** To check the order of the queries we can use regex to find
521 * all the row items in an array and then compare the items
522 * one by one in the order we expect it
523 * @reference https://github.com/testing-library/react-testing-library/issues/313#issuecomment-625294327
524 */
525 queries = await screen.findAllByText(/\["query-[1-3]"\]/)
526 expect(queries[0]?.textContent).toEqual(query1Hash)
527 expect(queries[1]?.textContent).toEqual(query2Hash)
528 expect(queries[2]?.textContent).toEqual(query3Hash)
529β
530 // Wait for the queries to be resolved
531 await screen.findByText(/query-1-result query-2-result query-3-result/i)
532β
533 // When sorted by the last updated date the queries are sorted by the time
534 // they were updated and since the query-2 takes longest time to complete
535 // and query-1 the shortest, so the order is -> query-2, query-3, query-1
536 fireEvent.change(sortSelect, { target: { value: 'Last Updated' } })
537β
538 queries = await screen.findAllByText(/\["query-[1-3]"\]/)
539 expect(queries[0]?.textContent).toEqual(query2Hash)
540 expect(queries[1]?.textContent).toEqual(query3Hash)
541 expect(queries[2]?.textContent).toEqual(query1Hash)
542β
543 // When sorted by the status and then last updated date the queries
544 // query-3 takes precedence because its stale time being infinity, it
545 // always remains fresh, the rest of the queries are sorted by their last
546 // updated time, so the resulting order is -> query-3, query-2, query-1
547 fireEvent.change(sortSelect, {
548 target: { value: 'Status > Last Updated' },
549 })
550β
551 queries = await screen.findAllByText(/\["query-[1-3]"\]/)
552 expect(queries[0]?.textContent).toEqual(query3Hash)
553 expect(queries[1]?.textContent).toEqual(query2Hash)
554 expect(queries[2]?.textContent).toEqual(query1Hash)
555β
556 // Switch the order form ascending to descending and expect the
557 // query order to be reversed from previous state
558 fireEvent.click(screen.getByRole('button', { name: /β¬ asc/i }))
559β
560 queries = await screen.findAllByText(/\["query-[1-3]"\]/)
561 expect(queries[0]?.textContent).toEqual(query1Hash)
562 expect(queries[1]?.textContent).toEqual(query2Hash)
563 expect(queries[2]?.textContent).toEqual(query3Hash)
564 })
565β
566 it('should initialize filtering and sorting values with defaults when they are not stored in localstorage', () => {
567 localStorage.removeItem('reactQueryDevtoolsBaseSort')
568 localStorage.removeItem('reactQueryDevtoolsSortFn')
569 localStorage.removeItem('reactQueryDevtoolsFilter')
570β
571 const { queryClient } = createQueryClient()
572β
573 function Page() {
574 const { data = 'default' } = useQuery(['check'], async () => {
575 await sleep(10)
576 return 'test'
577 })
578β
579 return (
580 <div>
581 <h1>{data}</h1>
582 </div>
583 )
584 }
585β
586 renderWithClient(queryClient, <Page />, {
587 initialIsOpen: true,
588 })
589β
590 const filterInput: HTMLInputElement =
591 screen.getByLabelText(/Filter by queryhash/i)
592 expect(filterInput.value).toEqual('')
593β
594 const sortCombobox: HTMLSelectElement =
595 screen.getByLabelText(/Sort queries/i)
596 expect(sortCombobox.value).toEqual(Object.keys(sortFns)[0])
597β
598 expect(screen.getByRole('button', { name: /Asc/i })).toBeInTheDocument()
599β
600 const detailsPanel = screen.queryByText(/Query Details/i)
601 expect(detailsPanel).not.toBeInTheDocument()
602 })
603β
604 it('should initialize sorting values with ones stored in localstorage', async () => {
605 localStorage.setItem('reactQueryDevtoolsBaseSort', 'true')
606 localStorage.setItem(
607 'reactQueryDevtoolsSortFn',
608 JSON.stringify(Object.keys(sortFns)[1]),
609 )
610β
611 const { queryClient } = createQueryClient()
612β
613 function Page() {
614 const { data = 'default' } = useQuery(['check'], async () => {
615 await sleep(10)
616 return 'test'
617 })
618β
619 return (
620 <div>
621 <h1>{data}</h1>
622 </div>
623 )
624 }
625β
626 renderWithClient(queryClient, <Page />, {
627 initialIsOpen: true,
628 })
629β
630 const sortCombobox: HTMLSelectElement =
631 screen.getByLabelText(/Sort queries/i)
632 expect(sortCombobox.value).toEqual(Object.keys(sortFns)[1])
633β
634 expect(screen.getByRole('button', { name: /Desc/i })).toBeInTheDocument()
635 })
636β
637 it('should initialize filter value with one stored in localstorage', () => {
638 localStorage.setItem('reactQueryDevtoolsFilter', JSON.stringify('posts'))
639β
640 const { queryClient } = createQueryClient()
641β
642 function Page() {
643 const { data = 'default' } = useQuery(['check'], async () => {
644 await sleep(10)
645 return 'test'
646 })
647β
648 return (
649 <div>
650 <h1>{data}</h1>
651 </div>
652 )
653 }
654β
655 renderWithClient(queryClient, <Page />, {
656 initialIsOpen: true,
657 })
658β
659 const filterInput: HTMLInputElement =
660 screen.getByLabelText(/Filter by queryhash/i)
661 expect(filterInput.value).toEqual('posts')
662 })
663β
664 it('should not show queries after clear', async () => {
665 const { queryClient, queryCache } = createQueryClient()
666β
667 function Page() {
668 const query1Result = useQuery(['query-1'], async () => {
669 return 'query-1-result'
670 })
671 const query2Result = useQuery(['query-2'], async () => {
672 return 'query-2-result'
673 })
674 const query3Result = useQuery(['query-3'], async () => {
675 return 'query-3-result'
676 })
677β
678 return (
679 <div>
680 <h1>
681 {query1Result.data} {query2Result.data} {query3Result.data}{' '}
682 </h1>
683 </div>
684 )
685 }
686β
687 renderWithClient(queryClient, <Page />)
688β
689 fireEvent.click(
690 screen.getByRole('button', { name: /open react query devtools/i }),
691 )
692β
693 expect(queryCache.getAll()).toHaveLength(3)
694β
695 const clearButton = screen.getByLabelText(/clear/i)
696 fireEvent.click(clearButton)
697β
698 expect(queryCache.getAll()).toHaveLength(0)
699 })
700β
701 it('style should have a nonce', async () => {
702 const { queryClient } = createQueryClient()
703β
704 function Page() {
705 return <div></div>
706 }
707β
708 const { container } = renderWithClient(queryClient, <Page />, {
709 styleNonce: 'test-nonce',
710 initialIsOpen: false,
711 })
712 const styleTag = container.querySelector('style')
713 expect(styleTag).toHaveAttribute('nonce', 'test-nonce')
714β
715 await screen.findByRole('button', { name: /react query devtools/i })
716 })
717β
718 describe('with custom context', () => {
719 it('should render without error when the custom context aligns', async () => {
720 const context = React.createContext<QueryClient | undefined>(undefined)
721 const { queryClient } = createQueryClient()
722β
723 function Page() {
724 const { data = 'default' } = useQuery(['check'], async () => 'test', {
725 context,
726 })
727β
728 return (
729 <div>
730 <h1>{data}</h1>
731 </div>
732 )
733 }
734β
735 renderWithClient(queryClient, <Page />, {
736 initialIsOpen: false,
737 context,
738 })
739β
740 await screen.findByRole('button', { name: /open react query devtools/i })
741 })
742β
743 it('should render with error when the custom context is not passed to useQuery', async () => {
744 const consoleErrorMock = jest.spyOn(console, 'error')
745 consoleErrorMock.mockImplementation(() => undefined)
746β
747 const context = React.createContext<QueryClient | undefined>(undefined)
748 const { queryClient } = createQueryClient()
749β
750 function Page() {
751 const { data = 'default' } = useQuery(['check'], async () => 'test', {
752 useErrorBoundary: true,
753 })
754β
755 return (
756 <div>
757 <h1>{data}</h1>
758 </div>
759 )
760 }
761β
762 const rendered = renderWithClient(
763 queryClient,
764 <ErrorBoundary fallbackRender={() => <div>error boundary</div>}>
765 <Page />
766 </ErrorBoundary>,
767 {
768 initialIsOpen: false,
769 context,
770 },
771 )
772β
773 await waitFor(() => rendered.getByText('error boundary'))
774β
775 consoleErrorMock.mockRestore()
776 })
777β
778 it('should render with error when the custom context is not passed to ReactQueryDevtools', async () => {
779 const consoleErrorMock = jest.spyOn(console, 'error')
780 consoleErrorMock.mockImplementation(() => undefined)
781β
782 const context = React.createContext<QueryClient | undefined>(undefined)
783 const { queryClient } = createQueryClient()
784β
785 function Page() {
786 const { data = 'default' } = useQuery(['check'], async () => 'test', {
787 useErrorBoundary: true,
788 context,
789 })
790β
791 return (
792 <div>
793 <h1>{data}</h1>
794 </div>
795 )
796 }
797β
798 const rendered = renderWithClient(
799 queryClient,
800 <ErrorBoundary fallbackRender={() => <div>error boundary</div>}>
801 <Page />
802 </ErrorBoundary>,
803 {
804 initialIsOpen: false,
805 },
806 )
807β
808 await waitFor(() => rendered.getByText('error boundary'))
809β
810 consoleErrorMock.mockRestore()
811 })
812 })
813β
814 it('should render a menu to select panel position', async () => {
815 const { queryClient } = createQueryClient()
816β
817 function Page() {
818 const { data = 'default' } = useQuery(['check'], async () => 'test')
819β
820 return (
821 <div>
822 <h1>{data}</h1>
823 </div>
824 )
825 }
826β
827 renderWithClient(queryClient, <Page />, {
828 initialIsOpen: true,
829 })
830β
831 const positionSelect = (await screen.findByLabelText(
832 'Panel position',
833 )) as HTMLSelectElement
834β
835 expect(positionSelect.value).toBe('bottom')
836 })
837β
838 it(`should render the panel to the left if panelPosition is set to 'left'`, async () => {
839 const { queryClient } = createQueryClient()
840β
841 function Page() {
842 const { data = 'default' } = useQuery(['check'], async () => 'test')
843β
844 return (
845 <div>
846 <h1>{data}</h1>
847 </div>
848 )
849 }
850β
851 renderWithClient(queryClient, <Page />, {
852 initialIsOpen: true,
853 panelPosition: 'left',
854 })
855β
856 const positionSelect = (await screen.findByLabelText(
857 'Panel position',
858 )) as HTMLSelectElement
859β
860 expect(positionSelect.value).toBe('left')
861β
862 const panel = (await screen.getByLabelText(
863 'React Query Devtools Panel',
864 )) as HTMLDivElement
865β
866 expect(panel.style.left).toBe('0px')
867 expect(panel.style.width).toBe('500px')
868 expect(panel.style.height).toBe('100vh')
869 })
870β
871 it('should change the panel position if user select different option from the menu', async () => {
872 const { queryClient } = createQueryClient()
873β
874 function Page() {
875 const { data = 'default' } = useQuery(['check'], async () => 'test')
876β
877 return (
878 <div>
879 <h1>{data}</h1>
880 </div>
881 )
882 }
883β
884 renderWithClient(queryClient, <Page />, {
885 initialIsOpen: true,
886 })
887β
888 const positionSelect = (await screen.findByLabelText(
889 'Panel position',
890 )) as HTMLSelectElement
891β
892 expect(positionSelect.value).toBe('bottom')
893β
894 const panel = (await screen.getByLabelText(
895 'React Query Devtools Panel',
896 )) as HTMLDivElement
897β
898 expect(panel.style.bottom).toBe('0px')
899 expect(panel.style.height).toBe('500px')
900 expect(panel.style.width).toBe('100%')
901β
902 await act(async () => {
903 fireEvent.change(positionSelect, { target: { value: 'right' } })
904 })
905β
906 expect(positionSelect.value).toBe('right')
907β
908 expect(panel.style.right).toBe('0px')
909 expect(panel.style.width).toBe('500px')
910 expect(panel.style.height).toBe('100vh')
911 })
912β
913 it('should restore parent element padding after closing', async () => {
914 const { queryClient } = createQueryClient()
915β
916 function Page() {
917 const { data = 'default' } = useQuery(['check'], async () => 'test')
918β
919 return (
920 <div>
921 <h1>{data}</h1>
922 </div>
923 )
924 }
925β
926 const parentElementTestid = 'parentElement'
927 const parentPaddings = {
928 paddingTop: '428px',
929 paddingBottom: '39px',
930 paddingLeft: '-373px',
931 paddingRight: '20%',
932 }
933β
934 function Parent({ children }: { children: React.ReactElement }) {
935 return (
936 <div data-testid={parentElementTestid} style={parentPaddings}>
937 {children}
938 </div>
939 )
940 }
941β
942 renderWithClient(
943 queryClient,
944 <Page />,
945 {
946 initialIsOpen: true,
947 panelPosition: 'bottom',
948 },
949 { wrapper: Parent },
950 )
951β
952 const parentElement = screen.getByTestId(parentElementTestid)
953 expect(parentElement).toHaveStyle({
954 paddingTop: '0px',
955 paddingLeft: '0px',
956 paddingRight: '0px',
957 paddingBottom: defaultPanelSize,
958 })
959β
960 fireEvent.click(screen.getByRole('button', { name: /^close$/i }))
961 expect(parentElement).toHaveStyle(parentPaddings)
962 })
963β
964 it('should simulate loading state', async () => {
965 const { queryClient } = createQueryClient()
966 let count = 0
967 function App() {
968 const { data, fetchStatus } = useQuery(['key'], () => {
969 count++
970 return Promise.resolve('test')
971 })
972β
973 return (
974 <div>
975 <h1>
976 {data ?? 'No data'}, {fetchStatus}
977 </h1>
978 </div>
979 )
980 }
981β
982 renderWithClient(queryClient, <App />, {
983 initialIsOpen: true,
984 })
985β
986 await screen.findByRole('heading', { name: /test/i })
987β
988 const loadingButton = await screen.findByRole('button', {
989 name: 'Trigger loading',
990 })
991 fireEvent.click(loadingButton)
992β
993 await waitFor(() => {
994 expect(screen.getByText('Restore loading')).toBeInTheDocument()
995 })
996β
997 await waitFor(() => {
998 expect(screen.getByText('No data, fetching')).toBeInTheDocument()
999 })
1000β
1001 fireEvent.click(screen.getByRole('button', { name: /restore loading/i }))
1002β
1003 await waitFor(() => {
1004 expect(screen.getByText('test, idle')).toBeInTheDocument()
1005 })
1006β
1007 expect(count).toBe(2)
1008 })
1009β
1010 it('should simulate error state', async () => {
1011 const { queryClient } = createQueryClient()
1012 function App() {
1013 const { status, error } = useQuery(['key'], () => {
1014 return Promise.resolve('test')
1015 })
1016β
1017 return (
1018 <div>
1019 <h1>
1020 {!!error ? 'Some error' : 'No error'}, {status}
1021 </h1>
1022 </div>
1023 )
1024 }
1025β
1026 renderWithClient(queryClient, <App />, {
1027 initialIsOpen: true,
1028 })
1029β
1030 const errorButton = await screen.findByRole('button', {
1031 name: 'Trigger error',
1032 })
1033 fireEvent.click(errorButton)
1034β
1035 await waitFor(() => {
1036 expect(screen.getByText('Restore error')).toBeInTheDocument()
1037 })
1038β
1039 await waitFor(() => {
1040 expect(screen.getByText('Some error, error')).toBeInTheDocument()
1041 })
1042β
1043 fireEvent.click(screen.getByRole('button', { name: /Restore error/i }))
1044β
1045 await waitFor(() => {
1046 expect(screen.getByText('No error, success')).toBeInTheDocument()
1047 })
1048 })
1049β
1050 it('should can simulate a specific error', async () => {
1051 const { queryClient } = createQueryClient()
1052β
1053 function App() {
1054 const { status, error } = useQuery(['key'], () => {
1055 return Promise.resolve('test')
1056 })
1057β
1058 return (
1059 <div data-testid="test">
1060 <h1>
1061 {error instanceof CustomError
1062 ? error.message.toString()
1063 : 'No error'}
1064 , {status}
1065 </h1>
1066 </div>
1067 )
1068 }
1069β
1070 renderWithClient(queryClient, <App />, {
1071 initialIsOpen: true,
1072 errorTypes: [
1073 {
1074 name: 'error1',
1075 initializer: () => new CustomError('error1'),
1076 },
1077 ],
1078 })
1079β
1080 const errorOption = await screen.findByLabelText('Trigger error:')
1081β
1082 UserEvent.selectOptions(errorOption, 'error1')
1083β
1084 await waitFor(() => {
1085 expect(screen.getByText('error1, error')).toBeInTheDocument()
1086 })
1087β
1088 fireEvent.click(screen.getByRole('button', { name: /Restore error/i }))
1089β
1090 await waitFor(() => {
1091 expect(screen.getByText('No error, success')).toBeInTheDocument()
1092 })
1093 })
1094β
1095 it('should not refetch when already restoring a query', async () => {
1096 const { queryClient } = createQueryClient()
1097β
1098 let count = 0
1099 let resolvePromise: (value: unknown) => void = () => undefined
1100β
1101 function App() {
1102 const { data } = useQuery(['key'], () => {
1103 count++
1104β
1105 // Resolve the promise immediately when
1106 // the query is fetched for the first time
1107 if (count === 1) {
1108 return Promise.resolve('test')
1109 }
1110β
1111 return new Promise((resolve) => {
1112 // Do not resolve immediately and store the
1113 // resolve function to resolve the promise later
1114 resolvePromise = resolve
1115 })
1116 })
1117β
1118 return (
1119 <div>
1120 <h1>{typeof data === 'string' ? data : 'No data'}</h1>
1121 </div>
1122 )
1123 }
1124β
1125 renderWithClient(queryClient, <App />, {
1126 initialIsOpen: true,
1127 })
1128β
1129 const loadingButton = await screen.findByRole('button', {
1130 name: 'Trigger loading',
1131 })
1132 fireEvent.click(loadingButton)
1133β
1134 await waitFor(() => {
1135 expect(screen.getByText('Restore loading')).toBeInTheDocument()
1136 })
1137β
1138 // Click the restore loading button twice and only resolve query promise
1139 // after the second click.
1140 fireEvent.click(screen.getByRole('button', { name: /restore loading/i }))
1141 fireEvent.click(screen.getByRole('button', { name: /restore loading/i }))
1142 resolvePromise('test')
1143β
1144 expect(count).toBe(2)
1145 })
1146})