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

devtools.test.tsx

1,146 lines30.3 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 type { QueryClient } from '@tanstack/react-query'
6import { useQuery } from '@tanstack/react-query'
7import { defaultPanelSize, sortFns } from '../utils'
8import {
9 getByTextContent,
10 renderWithClient,
11 sleep,
12 createQueryClient,
13} from './utils'
14import UserEvent from '@testing-library/user-event'
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 }
22​
23class CustomError extends Error {
24 constructor(message: string) {
25 super(message)
26 this.name = 'CustomError'
27 }
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>
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>
1069​
1070 renderWithClient(queryClient, <App />, {
1071 initialIsOpen: true,
1072 errorTypes: [
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')
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>
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 })