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

devtools.test.tsx

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