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

devtools.test.tsx

660 lines18.0 KB

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