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

Devtools.test.tsx

1,467 lines50.8 KB

1import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
2import {
3 QueryClient,
4 QueryObserver,
5 dehydrate,
6 hydrate,
7 noop,
8 onlineManager,
9} from '@tanstack/query-core'
10import { fireEvent, render } from '@solidjs/testing-library'
11import { createLocalStorage } from '@solid-primitives/storage'
12import { Devtools } from '../Devtools'
13import {
14 DevtoolsStateProvider,
15 PiPProvider,
16 QueryDevtoolsContext,
17 ThemeContext,
18} from '../contexts'
19import type { QueryDevtoolsProps } from '../contexts'
20​
21// `solid-transition-group` internally imports from
22// `@solid-primitives/transition-group`, whose `exports` field points at
23// `src/index.ts` (not published) under a `@solid-primitives/source` condition
24// that Vite can't fall through, so we stub it with a transparent pass-through.
25vi.mock('solid-transition-group', () => ({
26 TransitionGroup: (props: { children: unknown }) => props.children,
27}))
28​
29// `goober` compiles every `css\`...\`` template literal at mount time
30// (template parsing + class hashing + style serialization), which
31// dominates mount cost and produces no value for label/role-based
32// assertions, so we replace it with a no-op factory.
33vi.mock('goober', () => {
34 let counter = 0
35 const css = Object.assign(() => `tsqd-${++counter}`, {
36 bind: () => css,
37 })
38 return { css, glob: () => {}, setup: () => {} }
39})
40​
41describe('Devtools', () => {
42 const storage: { [key: string]: string } = {}
43 let queryClient: QueryClient
44 let previousRootFontSize = ''
45​
46 beforeEach(() => {
47 vi.useFakeTimers()
48 previousRootFontSize = document.documentElement.style.fontSize
49 vi.stubGlobal('localStorage', {
50 getItem: (key: string) =>
51 Object.prototype.hasOwnProperty.call(storage, key)
52 ? storage[key]
53 : null,
54 setItem: (key: string, value: string) => {
55 storage[key] = value
56 },
57 removeItem: (key: string) => {
58 delete storage[key]
59 },
60 clear: () => {
61 Object.keys(storage).forEach((key) => delete storage[key])
62 },
63 })
64 vi.stubGlobal(
65 'matchMedia',
66 vi.fn().mockImplementation((query: string) => ({
67 matches: false,
68 media: query,
69 onchange: null,
70 addEventListener: vi.fn(),
71 removeEventListener: vi.fn(),
72 addListener: vi.fn(),
73 removeListener: vi.fn(),
74 dispatchEvent: vi.fn(),
75 })),
76 )
77 vi.stubGlobal(
78 'ResizeObserver',
79 class {
80 callback: ResizeObserverCallback
81 constructor(callback: ResizeObserverCallback) {
82 this.callback = callback
83 }
84 observe = vi.fn((target: Element) => {
85 this.callback(
86 [
87 {
88 target,
89 contentRect: { width: 1000, height: 500 } as DOMRectReadOnly,
90 } as ResizeObserverEntry,
91 ],
92 // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
93 this as unknown as ResizeObserver,
94 )
95 })
96 unobserve = vi.fn()
97 disconnect = vi.fn()
98 },
99 )
100 queryClient = new QueryClient()
101 document.documentElement.style.fontSize = '16px'
102 })
103​
104 afterEach(() => {
105 vi.unstubAllGlobals()
106 Object.keys(storage).forEach((key) => delete storage[key])
107 queryClient.clear()
108 onlineManager.setOnline(true)
109 document.documentElement.style.fontSize = previousRootFontSize
110 vi.useRealTimers()
111 })
112​
113 function renderDevtools(
114 overrides: Partial<QueryDevtoolsProps> = {},
115 initialStorage: Record<string, string> = {},
116 ) {
117 Object.entries(initialStorage).forEach(([key, value]) => {
118 localStorage.setItem(key, value)
119 })
120 return render(() => {
121 const [localStore, setLocalStore] = createLocalStorage({
122 prefix: 'TanstackQueryDevtools',
123 })
124 return (
125 <QueryDevtoolsContext.Provider
126 value={{
127 client: queryClient,
128 queryFlavor: 'TanStack Query',
129 version: '5',
130 onlineManager,
131 ...overrides,
132 }}
133 >
134 <DevtoolsStateProvider>
135 <PiPProvider localStore={localStore} setLocalStore={setLocalStore}>
136 <ThemeContext.Provider value={() => 'dark'}>
137 <Devtools
138 localStore={localStore}
139 setLocalStore={setLocalStore}
140 />
141 </ThemeContext.Provider>
142 </PiPProvider>
143 </DevtoolsStateProvider>
144 </QueryDevtoolsContext.Provider>
145 )
146 })
147 }
148​
149 describe('initial state', () => {
150 it('should render the open devtools button', () => {
151 const rendered = renderDevtools()
152​
153 expect(
154 rendered.getByLabelText('Open Tanstack query devtools'),
155 ).toBeInTheDocument()
156 })
157​
158 it('should not render the panel by default', () => {
159 const rendered = renderDevtools()
160​
161 expect(
162 rendered.queryByLabelText('Tanstack query devtools'),
163 ).not.toBeInTheDocument()
164 })
165​
166 it('should render the panel when "initialIsOpen" is "true"', () => {
167 const rendered = renderDevtools({ initialIsOpen: true })
168​
169 expect(
170 rendered.getByLabelText('Tanstack query devtools'),
171 ).toBeInTheDocument()
172 })
173​
174 it('should render the panel when "localStore.open" is "true"', () => {
175 const rendered = renderDevtools(
176 {},
177 { 'TanstackQueryDevtools.open': 'true' },
178 )
179​
180 expect(
181 rendered.getByLabelText('Tanstack query devtools'),
182 ).toBeInTheDocument()
183 })
184​
185 it('should not render the panel when "localStore.open" is "false" even if "initialIsOpen" is "true"', () => {
186 const rendered = renderDevtools(
187 { initialIsOpen: true },
188 { 'TanstackQueryDevtools.open': 'false' },
189 )
190​
191 expect(
192 rendered.queryByLabelText('Tanstack query devtools'),
193 ).not.toBeInTheDocument()
194 })
195 })
196​
197 describe('open and close', () => {
198 it('should render the panel when the open button is clicked', () => {
199 const rendered = renderDevtools()
200​
201 fireEvent.click(rendered.getByLabelText('Open Tanstack query devtools'))
202 expect(
203 rendered.getByLabelText('Tanstack query devtools'),
204 ).toBeInTheDocument()
205 })
206​
207 it('should hide the open button when the panel is open', () => {
208 const rendered = renderDevtools()
209​
210 fireEvent.click(rendered.getByLabelText('Open Tanstack query devtools'))
211 expect(
212 rendered.queryByLabelText('Open Tanstack query devtools'),
213 ).not.toBeInTheDocument()
214 })
215​
216 it('should hide the panel when the close button is clicked', () => {
217 const rendered = renderDevtools({ initialIsOpen: true })
218​
219 fireEvent.click(rendered.getByLabelText('Close tanstack query devtools'))
220 expect(
221 rendered.queryByLabelText('Tanstack query devtools'),
222 ).not.toBeInTheDocument()
223 })
224​
225 it('should render the open button after the panel is closed', () => {
226 const rendered = renderDevtools({ initialIsOpen: true })
227​
228 fireEvent.click(rendered.getByLabelText('Close tanstack query devtools'))
229 expect(
230 rendered.getByLabelText('Open Tanstack query devtools'),
231 ).toBeInTheDocument()
232 })
233​
234 it('should persist "open" as "true" to "localStorage" when the open button is clicked', () => {
235 const rendered = renderDevtools()
236​
237 fireEvent.click(rendered.getByLabelText('Open Tanstack query devtools'))
238 expect(localStorage.getItem('TanstackQueryDevtools.open')).toBe('true')
239 })
240​
241 it('should persist "open" as "false" to "localStorage" when the close button is clicked', () => {
242 const rendered = renderDevtools({ initialIsOpen: true })
243​
244 fireEvent.click(rendered.getByLabelText('Close tanstack query devtools'))
245 expect(localStorage.getItem('TanstackQueryDevtools.open')).toBe('false')
246 })
247 })
248​
249 describe('query list', () => {
250 it('should render a row for each query in the cache', () => {
251 queryClient.setQueryData(['posts'], [{ id: 1 }])
252 queryClient.setQueryData(['users', 'me'], { id: 'u1' })
253 const rendered = renderDevtools({ initialIsOpen: true })
254​
255 expect(
256 rendered.getByLabelText(/Query key \["posts"\]/),
257 ).toBeInTheDocument()
258 expect(
259 rendered.getByLabelText(/Query key \["users","me"\]/),
260 ).toBeInTheDocument()
261 })
262​
263 it('should reflect a newly added query reactively', () => {
264 const rendered = renderDevtools({ initialIsOpen: true })
265​
266 expect(
267 rendered.queryByLabelText(/Query key \["new"\]/),
268 ).not.toBeInTheDocument()
269​
270 queryClient.setQueryData(['new'], 'hello')
271​
272 expect(rendered.getByLabelText(/Query key \["new"\]/)).toBeInTheDocument()
273 })
274​
275 it('should filter queries by "queryHash"', () => {
276 queryClient.setQueryData(['posts'], [])
277 queryClient.setQueryData(['users'], [])
278 const rendered = renderDevtools({ initialIsOpen: true })
279​
280 fireEvent.input(rendered.getByLabelText('Filter queries by query key'), {
281 target: { value: 'posts' },
282 })
283 expect(
284 rendered.getByLabelText(/Query key \["posts"\]/),
285 ).toBeInTheDocument()
286 expect(
287 rendered.queryByLabelText(/Query key \["users"\]/),
288 ).not.toBeInTheDocument()
289 })
290​
291 it('should clear all queries when the clear cache button is clicked', () => {
292 queryClient.setQueryData(['posts'], [])
293 queryClient.setQueryData(['users'], [])
294 const rendered = renderDevtools({ initialIsOpen: true })
295​
296 fireEvent.click(rendered.getByLabelText('Clear query cache'))
297 expect(
298 rendered.queryByLabelText(/Query key \["posts"\]/),
299 ).not.toBeInTheDocument()
300 expect(
301 rendered.queryByLabelText(/Query key \["users"\]/),
302 ).not.toBeInTheDocument()
303 })
304​
305 it('should dispatch a "CLEAR_MUTATION_CACHE" event when clear cache is clicked in mutations view', () => {
306 const rendered = renderDevtools({ initialIsOpen: true })
307 fireEvent.click(rendered.getByText('Mutations'))
308​
309 const listener = vi.fn()
310 window.addEventListener('@tanstack/query-devtools-event', listener)
311​
312 try {
313 fireEvent.click(rendered.getByLabelText('Clear query cache'))
314​
315 const dispatched = listener.mock.calls.some(
316 ([e]) => (e as CustomEvent).detail.type === 'CLEAR_MUTATION_CACHE',
317 )
318 expect(dispatched).toBe(true)
319 } finally {
320 window.removeEventListener('@tanstack/query-devtools-event', listener)
321 }
322 })
323​
324 it('should render a query row when a hydrated query uses a custom hash function', async () => {
325 queryClient.query({
326 queryKey: ['posts'],
327 queryFn: () => [{ id: 1 }],
328 queryKeyHashFn: () => 'custom-posts-hash',
329 })
330 await vi.advanceTimersByTimeAsync(0)
331 const dehydratedState = dehydrate(queryClient)
332​
333 queryClient = new QueryClient()
334 hydrate(queryClient, dehydratedState)
335​
336 const rendered = renderDevtools({ initialIsOpen: true })
337​
338 expect(
339 rendered.getByLabelText(/Query key custom-posts-hash/),
340 ).toBeInTheDocument()
341 })
342 })
343​
344 describe('view toggle', () => {
345 it('should switch to mutations view when the mutations toggle is clicked', () => {
346 const rendered = renderDevtools({ initialIsOpen: true })
347​
348 fireEvent.click(rendered.getByText('Mutations'))
349 expect(
350 rendered.container.querySelector('.tsqd-mutations-container'),
351 ).not.toBeNull()
352 })
353​
354 it('should render mutations in the mutations view', async () => {
355 const rendered = renderDevtools({ initialIsOpen: true })
356​
357 fireEvent.click(rendered.getByText('Mutations'))
358​
359 const mutation = queryClient.getMutationCache().build(queryClient, {
360 mutationKey: ['add-post'],
361 mutationFn: () => Promise.resolve('ok'),
362 })
363 mutation.execute({})
364 await vi.advanceTimersByTimeAsync(0)
365 expect(
366 rendered.getByLabelText(/Mutation submitted at/),
367 ).toBeInTheDocument()
368 })
369​
370 it('should render an idle mutation that has been built but not executed', async () => {
371 const rendered = renderDevtools({ initialIsOpen: true })
372​
373 fireEvent.click(rendered.getByText('Mutations'))
374​
375 queryClient.getMutationCache().build(queryClient, {
376 mutationKey: ['idle-mut'],
377 mutationFn: () => Promise.resolve('ok'),
378 })
379 await vi.advanceTimersByTimeAsync(0)
380 expect(
381 rendered.getByLabelText(/Mutation submitted at/),
382 ).toBeInTheDocument()
383 })
384 })
385​
386 describe('disabled and static queries', () => {
387 it('should mark a disabled query in the row label', () => {
388 const observer = queryClient.getQueryCache().build(queryClient, {
389 queryKey: ['disabled-q'],
390 queryFn: () => 'x',
391 })
392 observer.setOptions({
393 ...observer.options,
394 enabled: false,
395 } as typeof observer.options)
396 observer.setState({ ...observer.state, data: 'x' })
397 const rendered = renderDevtools({ initialIsOpen: true })
398​
399 expect(rendered.getByLabelText(/disabled/)).toBeInTheDocument()
400 })
401​
402 it('should render a "static" indicator for a query with "staleTime: \'static\'"', () => {
403 const query = queryClient.getQueryCache().build(queryClient, {
404 queryKey: ['static-q'],
405 queryFn: () => 'x',
406 })
407 const observer = new QueryObserver(queryClient, {
408 queryKey: ['static-q'],
409 queryFn: () => 'x',
410 staleTime: 'static',
411 })
412 query.addObserver(observer)
413 query.setState({ ...query.state, data: 'x' })
414 const rendered = renderDevtools({ initialIsOpen: true })
415​
416 expect(rendered.getByText('static')).toBeInTheDocument()
417 expect(rendered.getByLabelText(/, static/)).toBeInTheDocument()
418 })
419​
420 it('should render a query row when an object query key is mutated in place', () => {
421 const filters = { page: 1 }
422 queryClient.setQueryData(['mutable-key', filters], 'x')
423 filters.page = 2
424​
425 const rendered = renderDevtools({ initialIsOpen: true })
426​
427 expect(
428 rendered.getByLabelText(/Query key \["mutable-key",\{"page":1\}\]/),
429 ).toBeInTheDocument()
430 })
431 })
432​
433 describe('picture-in-picture', () => {
434 type FakePipWindow = Pick<
435 Window,
436 | 'document'
437 | 'innerWidth'
438 | 'innerHeight'
439 | 'addEventListener'
440 | 'removeEventListener'
441 | 'close'
442 >
443​
444 function stubPipWindow(
445 overrides: Partial<
446 Pick<FakePipWindow, 'innerWidth' | 'innerHeight'>
447 > = {},
448 ) {
449 const pipDocument = document.implementation.createHTMLDocument('PiP')
450 const listeners = new Map<string, EventListener>()
451 const fakeWindow: FakePipWindow = {
452 document: pipDocument,
453 innerWidth: 800,
454 innerHeight: 600,
455 addEventListener: vi.fn((event: string, handler: EventListener) => {
456 listeners.set(event, handler)
457 }),
458 removeEventListener: vi.fn((event: string) => {
459 listeners.delete(event)
460 }),
461 close: vi.fn(),
462 ...overrides,
463 }
464 const open = vi.fn(() => fakeWindow)
465 vi.stubGlobal('open', open)
466 return {
467 pipDocument,
468 fakeWindow,
469 open,
470 fire: (event: string) => {
471 listeners.get(event)?.(new Event(event))
472 },
473 }
474 }
475​
476 it('should open a PiP window when the picture-in-picture button is clicked', () => {
477 const { open } = stubPipWindow()
478 const rendered = renderDevtools({ initialIsOpen: true })
479​
480 fireEvent.click(
481 rendered.getByLabelText('Open in picture-in-picture mode'),
482 )
483 expect(open).toHaveBeenCalledWith(
484 '',
485 'TSQD-Devtools-Panel',
486 expect.stringMatching(/^width=\d+,height=\d+,popup$/),
487 )
488 expect(localStorage.getItem('TanstackQueryDevtools.pip_open')).toBe(
489 'true',
490 )
491 })
492​
493 it('should hide the in-page panel while a PiP window is open', () => {
494 stubPipWindow()
495 const rendered = renderDevtools({ initialIsOpen: true })
496​
497 fireEvent.click(
498 rendered.getByLabelText('Open in picture-in-picture mode'),
499 )
500 expect(
501 rendered.container.querySelector('.tsqd-main-panel-container'),
502 ).toBeNull()
503 })
504​
505 it('should restore the in-page panel when the PiP window is closed', () => {
506 const { fire } = stubPipWindow()
507 const rendered = renderDevtools({ initialIsOpen: true })
508​
509 fireEvent.click(
510 rendered.getByLabelText('Open in picture-in-picture mode'),
511 )
512 fire('pagehide')
513 expect(
514 rendered.getByLabelText('Open in picture-in-picture mode'),
515 ).toBeInTheDocument()
516 })
517​
518 it('should render the PiP panel with the narrow layout when the PiP window is below the second breakpoint', () => {
519 // secondBreakpoint = 796; pick a width comfortably below it so the
520 // PiP panel evaluates its narrow (`flex-direction: column`) branch.
521 const { pipDocument } = stubPipWindow({ innerWidth: 500 })
522 queryClient.setQueryData(['narrow-pip-query'], { hello: 'world' })
523 const rendered = renderDevtools({ initialIsOpen: true })
524​
525 fireEvent.click(
526 rendered.getByLabelText('Open in picture-in-picture mode'),
527 )
528 expect(
529 pipDocument.querySelector(
530 '[aria-label="Close Tanstack query devtools"]',
531 ),
532 ).not.toBeNull()
533 expect(
534 pipDocument.querySelector('[aria-label*="narrow-pip-query"]'),
535 ).not.toBeNull()
536 })
537 })
538​
539 describe('status counts', () => {
540 it('should render status count badges', () => {
541 const rendered = renderDevtools({ initialIsOpen: true })
542​
543 expect(rendered.getByLabelText(/Fresh: \d+/)).toBeInTheDocument()
544 expect(rendered.getByLabelText(/Stale: \d+/)).toBeInTheDocument()
545 expect(rendered.getByLabelText(/Fetching: \d+/)).toBeInTheDocument()
546 expect(rendered.getByLabelText(/Paused: \d+/)).toBeInTheDocument()
547 expect(rendered.getByLabelText(/Inactive: \d+/)).toBeInTheDocument()
548 })
549​
550 it('should reflect the inactive count when a query is added without observers', () => {
551 const rendered = renderDevtools({ initialIsOpen: true })
552​
553 expect(rendered.getByLabelText('Inactive: 0')).toBeInTheDocument()
554​
555 queryClient.setQueryData(['posts'], [{ id: 1 }])
556​
557 expect(rendered.getByLabelText('Inactive: 1')).toBeInTheDocument()
558 })
559 })
560​
561 describe('status tooltip', () => {
562 it('should show the tooltip on mouse enter and hide it on mouse leave when the panel is narrow', () => {
563 // Re-stub ResizeObserver with a narrow width (< secondBreakpoint = 796)
564 // so `showLabel()` is false and the tooltip is rendered conditionally on
565 // hover/focus.
566 vi.stubGlobal(
567 'ResizeObserver',
568 class {
569 callback: ResizeObserverCallback
570 constructor(callback: ResizeObserverCallback) {
571 this.callback = callback
572 }
573 observe = vi.fn((target: Element) => {
574 this.callback(
575 [
576 {
577 target,
578 contentRect: { width: 500, height: 500 } as DOMRectReadOnly,
579 } as ResizeObserverEntry,
580 ],
581 // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
582 this as unknown as ResizeObserver,
583 )
584 })
585 unobserve = vi.fn()
586 disconnect = vi.fn()
587 },
588 )
589​
590 const rendered = renderDevtools({ initialIsOpen: true })
591 const fresh = rendered.getByLabelText('Fresh: 0')
592​
593 expect(rendered.queryByRole('tooltip')).not.toBeInTheDocument()
594​
595 fireEvent.mouseEnter(fresh)
596 expect(rendered.getByRole('tooltip')).toBeInTheDocument()
597​
598 fireEvent.mouseLeave(fresh)
599 expect(rendered.queryByRole('tooltip')).not.toBeInTheDocument()
600 })
601​
602 it('should show the tooltip on focus and hide it on blur when the panel is narrow', () => {
603 vi.stubGlobal(
604 'ResizeObserver',
605 class {
606 callback: ResizeObserverCallback
607 constructor(callback: ResizeObserverCallback) {
608 this.callback = callback
609 }
610 observe = vi.fn((target: Element) => {
611 this.callback(
612 [
613 {
614 target,
615 contentRect: { width: 500, height: 500 } as DOMRectReadOnly,
616 } as ResizeObserverEntry,
617 ],
618 // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
619 this as unknown as ResizeObserver,
620 )
621 })
622 unobserve = vi.fn()
623 disconnect = vi.fn()
624 },
625 )
626​
627 const rendered = renderDevtools({ initialIsOpen: true })
628 const fresh = rendered.getByLabelText('Fresh: 0')
629​
630 expect(rendered.queryByRole('tooltip')).not.toBeInTheDocument()
631​
632 fireEvent.focus(fresh)
633 expect(rendered.getByRole('tooltip')).toBeInTheDocument()
634​
635 fireEvent.blur(fresh)
636 expect(rendered.queryByRole('tooltip')).not.toBeInTheDocument()
637 })
638 })
639​
640 describe('query details', () => {
641 it('should open the query details panel when a query row is clicked', () => {
642 queryClient.setQueryData(['posts'], [{ id: 1 }])
643 const rendered = renderDevtools({ initialIsOpen: true })
644​
645 fireEvent.click(rendered.getByLabelText(/Query key \["posts"\]/))
646 expect(rendered.getByText('Query Details')).toBeInTheDocument()
647 })
648​
649 it('should close the query details panel when the same row is clicked again', () => {
650 queryClient.setQueryData(['details-toggle'], [{ id: 1 }])
651 const rendered = renderDevtools({ initialIsOpen: true })
652​
653 fireEvent.click(rendered.getByLabelText(/Query key \["details-toggle"\]/))
654 fireEvent.click(rendered.getByLabelText(/Query key \["details-toggle"\]/))
655 expect(rendered.queryByText('Query Details')).not.toBeInTheDocument()
656 })
657 })
658​
659 describe('query actions', () => {
660 it('should remove the query when the "Remove" button is clicked', () => {
661 queryClient.setQueryData(['action-remove'], [{ id: 1 }])
662 const rendered = renderDevtools({ initialIsOpen: true })
663​
664 fireEvent.click(rendered.getByLabelText(/Query key \["action-remove"\]/))
665 fireEvent.click(rendered.getByText('Remove'))
666 expect(
667 rendered.queryByLabelText(/Query key \["action-remove"\]/),
668 ).not.toBeInTheDocument()
669 })
670​
671 it('should reset the query when the "Reset" button is clicked', () => {
672 queryClient.setQueryData(['action-reset'], [{ id: 1 }])
673 const rendered = renderDevtools({ initialIsOpen: true })
674​
675 fireEvent.click(rendered.getByLabelText(/Query key \["action-reset"\]/))
676 fireEvent.click(rendered.getByText('Reset'))
677 expect(queryClient.getQueryData(['action-reset'])).toBeUndefined()
678 })
679​
680 it('should invalidate the query when the "Invalidate" button is clicked', () => {
681 queryClient.setQueryData(['action-invalidate'], [{ id: 1 }])
682 const rendered = renderDevtools({ initialIsOpen: true })
683​
684 fireEvent.click(
685 rendered.getByLabelText(/Query key \["action-invalidate"\]/),
686 )
687 fireEvent.click(rendered.getByText('Invalidate'))
688 expect(
689 queryClient.getQueryState(['action-invalidate'])?.isInvalidated,
690 ).toBe(true)
691 })
692​
693 it('should dispatch a "REFETCH" event when "Refetch" is clicked', () => {
694 queryClient.setQueryData(['action-refetch'], [{ id: 1 }])
695 const rendered = renderDevtools({ initialIsOpen: true })
696​
697 const listener = vi.fn()
698 window.addEventListener('@tanstack/query-devtools-event', listener)
699​
700 try {
701 fireEvent.click(
702 rendered.getByLabelText(/Query key \["action-refetch"\]/),
703 )
704 fireEvent.click(rendered.getByText('Refetch'))
705​
706 const dispatched = listener.mock.calls.some(
707 ([e]) => (e as CustomEvent).detail.type === 'REFETCH',
708 )
709 expect(dispatched).toBe(true)
710 } finally {
711 window.removeEventListener('@tanstack/query-devtools-event', listener)
712 }
713 })
714​
715 it('should set the query status to "error" when "Trigger Error" is clicked', () => {
716 queryClient.setQueryData(['action-error'], [{ id: 1 }])
717 const rendered = renderDevtools({ initialIsOpen: true })
718​
719 fireEvent.click(rendered.getByLabelText(/Query key \["action-error"\]/))
720 fireEvent.click(rendered.getByText('Trigger Error'))
721 expect(queryClient.getQueryState(['action-error'])?.status).toBe('error')
722 })
723​
724 it('should restore the query status when "Restore Error" is clicked after "Trigger Error"', () => {
725 queryClient.setQueryData(['action-restore-error'], [{ id: 1 }])
726 const rendered = renderDevtools({ initialIsOpen: true })
727​
728 fireEvent.click(
729 rendered.getByLabelText(/Query key \["action-restore-error"\]/),
730 )
731 fireEvent.click(rendered.getByText('Trigger Error'))
732 fireEvent.click(rendered.getByText('Restore Error'))
733 expect(queryClient.getQueryState(['action-restore-error'])?.status).toBe(
734 'pending',
735 )
736 })
737​
738 it('should restore the previous query options when "Restore Loading" is clicked after "Trigger Loading"', async () => {
739 const queryFn = vi.fn(() => Promise.resolve('original'))
740 void queryClient
741 .query({
742 queryKey: ['action-restore-loading'],
743 queryFn,
744 })
745 .catch(noop)
746 await vi.advanceTimersByTimeAsync(0)
747 expect(queryFn).toHaveBeenCalledTimes(1)
748​
749 const rendered = renderDevtools({ initialIsOpen: true })
750​
751 fireEvent.click(
752 rendered.getByLabelText(/Query key \["action-restore-loading"\]/),
753 )
754​
755 // First click puts the query into a pending state with `data: undefined`
756 // and stashes the original options in `fetchMeta.__previousQueryOptions`.
757 fireEvent.click(rendered.getByText('Trigger Loading'))
758 expect(
759 queryClient.getQueryState(['action-restore-loading'])?.status,
760 ).toBe('pending')
761​
762 // Second click runs `restoreQueryAfterLoadingOrError`, which cancels the
763 // never-resolving fetch and refetches with the stashed options.
764 fireEvent.click(rendered.getByText('Restore Loading'))
765 await vi.advanceTimersByTimeAsync(0)
766 expect(queryFn).toHaveBeenCalledTimes(2)
767 expect(queryClient.getQueryData(['action-restore-loading'])).toBe(
768 'original',
769 )
770 })
771 })
772​
773 describe('mutation details', () => {
774 it('should open the mutation details panel when a mutation row is clicked', async () => {
775 const rendered = renderDevtools({ initialIsOpen: true })
776​
777 fireEvent.click(rendered.getByText('Mutations'))
778​
779 const mutation = queryClient.getMutationCache().build(queryClient, {
780 mutationKey: ['mutation-detail'],
781 mutationFn: () => Promise.resolve('ok'),
782 })
783 mutation.execute({})
784 await vi.advanceTimersByTimeAsync(0)
785​
786 fireEvent.click(rendered.getByLabelText(/Mutation submitted at/))
787 expect(rendered.getByText('Mutation Details')).toBeInTheDocument()
788 })
789 })
790​
791 describe('mutation sort order', () => {
792 it('should toggle the mutation sort order in the mutations view', () => {
793 const rendered = renderDevtools({ initialIsOpen: true })
794 fireEvent.click(rendered.getByText('Mutations'))
795​
796 fireEvent.click(rendered.getByLabelText(/Sort order/))
797 const afterFirstToggle = localStorage.getItem(
798 'TanstackQueryDevtools.mutationSortOrder',
799 )
800 expect(afterFirstToggle).not.toBeNull()
801​
802 fireEvent.click(rendered.getByLabelText(/Sort order/))
803 const afterSecondToggle = localStorage.getItem(
804 'TanstackQueryDevtools.mutationSortOrder',
805 )
806 expect(afterSecondToggle).not.toBe(afterFirstToggle)
807 })
808 })
809​
810 describe('mutation filter', () => {
811 it('should filter mutations by their "mutationKey"', async () => {
812 const rendered = renderDevtools({ initialIsOpen: true })
813 fireEvent.click(rendered.getByText('Mutations'))
814​
815 const matching = queryClient.getMutationCache().build(queryClient, {
816 mutationKey: ['filter-match'],
817 mutationFn: () => Promise.resolve('ok'),
818 })
819 const other = queryClient.getMutationCache().build(queryClient, {
820 mutationKey: ['filter-other'],
821 mutationFn: () => Promise.resolve('ok'),
822 })
823 matching.execute({})
824 other.execute({})
825 await vi.advanceTimersByTimeAsync(0)
826 expect(rendered.getAllByLabelText(/Mutation submitted at/)).toHaveLength(
827 2,
828 )
829​
830 fireEvent.input(rendered.getByLabelText('Filter queries by query key'), {
831 target: { value: 'filter-match' },
832 })
833 expect(rendered.getAllByLabelText(/Mutation submitted at/)).toHaveLength(
834 1,
835 )
836 })
837 })
838​
839 describe('data edit', () => {
840 it('should switch to data editor when "Bulk Edit Data" is clicked', () => {
841 queryClient.setQueryData(['edit-data'], { name: 'a' })
842 const rendered = renderDevtools({ initialIsOpen: true })
843​
844 fireEvent.click(rendered.getByLabelText(/Query key \["edit-data"\]/))
845 fireEvent.click(rendered.getByLabelText('Bulk Edit Data'))
846 expect(
847 rendered.getByLabelText('Edit query data as JSON'),
848 ).toBeInTheDocument()
849 })
850​
851 it('should save the edited data when the form is submitted', () => {
852 queryClient.setQueryData(['edit-save'], { name: 'a' })
853 const rendered = renderDevtools({ initialIsOpen: true })
854​
855 fireEvent.click(rendered.getByLabelText(/Query key \["edit-save"\]/))
856 fireEvent.click(rendered.getByLabelText('Bulk Edit Data'))
857​
858 const textarea = rendered.getByLabelText('Edit query data as JSON')
859 fireEvent.input(textarea, {
860 target: { value: JSON.stringify({ name: 'b' }) },
861 })
862 fireEvent.submit(textarea.closest('form')!)
863 expect(queryClient.getQueryData(['edit-save'])).toEqual({ name: 'b' })
864 })
865​
866 it('should set an error state when the edited data is invalid JSON', () => {
867 queryClient.setQueryData(['edit-invalid'], { name: 'a' })
868 const rendered = renderDevtools({ initialIsOpen: true })
869​
870 fireEvent.click(rendered.getByLabelText(/Query key \["edit-invalid"\]/))
871 fireEvent.click(rendered.getByLabelText('Bulk Edit Data'))
872​
873 const textarea = rendered.getByLabelText('Edit query data as JSON')
874 fireEvent.input(textarea, { target: { value: 'not json' } })
875 fireEvent.submit(textarea.closest('form')!)
876 expect(rendered.getByText('Invalid Value')).toBeInTheDocument()
877 })
878​
879 it('should clear the error state when the textarea is focused after a submit failure', () => {
880 queryClient.setQueryData(['edit-refocus'], { name: 'a' })
881 const rendered = renderDevtools({ initialIsOpen: true })
882​
883 fireEvent.click(rendered.getByLabelText(/Query key \["edit-refocus"\]/))
884 fireEvent.click(rendered.getByLabelText('Bulk Edit Data'))
885​
886 const textarea = rendered.getByLabelText('Edit query data as JSON')
887 fireEvent.input(textarea, { target: { value: 'not json' } })
888 fireEvent.submit(textarea.closest('form')!)
889 expect(rendered.getByText('Invalid Value')).toBeInTheDocument()
890​
891 fireEvent.focus(textarea)
892 expect(rendered.queryByText('Invalid Value')).toBeNull()
893 })
894​
895 it('should return to the data view when the editor "Cancel" button is clicked', () => {
896 queryClient.setQueryData(['edit-cancel'], { name: 'a' })
897 const rendered = renderDevtools({ initialIsOpen: true })
898​
899 fireEvent.click(rendered.getByLabelText(/Query key \["edit-cancel"\]/))
900 fireEvent.click(rendered.getByLabelText('Bulk Edit Data'))
901 expect(
902 rendered.getByLabelText('Edit query data as JSON'),
903 ).toBeInTheDocument()
904​
905 fireEvent.click(rendered.getByText('Cancel'))
906 expect(rendered.queryByLabelText('Edit query data as JSON')).toBeNull()
907 expect(rendered.getByLabelText('Bulk Edit Data')).toBeInTheDocument()
908 })
909 })
910​
911 describe('error type select', () => {
912 it('should render the error type select when "errorTypes" is provided', () => {
913 queryClient.setQueryData(['error-select'], [{ id: 1 }])
914 const rendered = renderDevtools({
915 initialIsOpen: true,
916 errorTypes: [
917 {
918 name: 'NetworkError',
919 initializer: () => new Error('Network'),
920 },
921 ],
922 })
923​
924 fireEvent.click(rendered.getByLabelText(/Query key \["error-select"\]/))
925 expect(
926 rendered.getByLabelText('Select error type to trigger'),
927 ).toBeInTheDocument()
928 })
929​
930 it('should trigger error when an error type is selected', () => {
931 queryClient.setQueryData(['error-select-trigger'], [{ id: 1 }])
932 const rendered = renderDevtools({
933 initialIsOpen: true,
934 errorTypes: [
935 {
936 name: 'NetworkError',
937 initializer: () => new Error('Network'),
938 },
939 ],
940 })
941​
942 fireEvent.click(
943 rendered.getByLabelText(/Query key \["error-select-trigger"\]/),
944 )
945 const select = rendered.getByLabelText('Select error type to trigger')
946 fireEvent.change(select, { target: { value: 'NetworkError' } })
947 expect(queryClient.getQueryState(['error-select-trigger'])?.status).toBe(
948 'error',
949 )
950 })
951 })
952​
953 describe('sort by', () => {
954 it('should change sort key when the sort dropdown is changed in queries view', () => {
955 const rendered = renderDevtools({ initialIsOpen: true })
956​
957 fireEvent.change(rendered.getByLabelText('Sort queries by'), {
958 target: { value: 'last updated' },
959 })
960 expect(localStorage.getItem('TanstackQueryDevtools.sort')).toBe(
961 'last updated',
962 )
963 })
964​
965 it('should change sort key when the sort dropdown is changed in mutations view', () => {
966 const rendered = renderDevtools({ initialIsOpen: true })
967 fireEvent.click(rendered.getByText('Mutations'))
968​
969 fireEvent.change(rendered.getByLabelText('Sort mutations by'), {
970 target: { value: 'last updated' },
971 })
972 expect(localStorage.getItem('TanstackQueryDevtools.mutationSort')).toBe(
973 'last updated',
974 )
975 })
976​
977 it('should hide disabled queries when "hideDisabledQueries" is enabled in localStorage', () => {
978 const disabled = new QueryObserver(queryClient, {
979 queryKey: ['hide-test-disabled'],
980 queryFn: () => 'x',
981 enabled: false,
982 })
983 const unsubscribe = disabled.subscribe(() => {})
984 queryClient.setQueryData(['hide-test-disabled'], 'x')
985 queryClient.setQueryData(['hide-test-active'], 'y')
986​
987 try {
988 const rendered = renderDevtools(
989 { initialIsOpen: true },
990 { 'TanstackQueryDevtools.hideDisabledQueries': 'true' },
991 )
992​
993 expect(
994 rendered.queryByLabelText(/Query key \["hide-test-disabled"\]/),
995 ).not.toBeInTheDocument()
996 expect(
997 rendered.getByLabelText(/Query key \["hide-test-active"\]/),
998 ).toBeInTheDocument()
999 } finally {
1000 unsubscribe()
1002 })
1003 })
1004​
1005 describe('sort order', () => {
1006 it('should toggle the sort order when the sort order button is clicked', () => {
1007 const rendered = renderDevtools({ initialIsOpen: true })
1008​
1009 fireEvent.click(rendered.getByLabelText(/Sort order/))
1010 const afterFirstToggle = localStorage.getItem(
1011 'TanstackQueryDevtools.sortOrder',
1013 expect(['1', '-1']).toContain(afterFirstToggle)
1014​
1015 fireEvent.click(rendered.getByLabelText(/Sort order/))
1016 const afterSecondToggle = localStorage.getItem(
1017 'TanstackQueryDevtools.sortOrder',
1019 expect(afterSecondToggle).toBe(afterFirstToggle === '1' ? '-1' : '1')
1020 })
1021 })
1022​
1023 describe('settings menu', () => {
1024 it('should show "Position" sub-trigger when the settings menu is opened', () => {
1025 const rendered = renderDevtools({ initialIsOpen: true })
1026​
1027 fireEvent.keyDown(rendered.getByLabelText('Open settings menu'), {
1028 key: 'Enter',
1029 })
1030​
1031 // The menu is rendered through a Portal mounted on `document.body`,
1032 // outside `rendered.container`, so look it up via `document` directly.
1033 expect(
1034 document.querySelector('.tsqd-settings-menu-sub-trigger-position'),
1035 ).not.toBeNull()
1036 })
1037​
1038 it('should open "Position" sub-menu when the sub-trigger is activated', () => {
1039 const rendered = renderDevtools({ initialIsOpen: true })
1040​
1041 fireEvent.keyDown(rendered.getByLabelText('Open settings menu'), {
1042 key: 'Enter',
1043 })
1044​
1045 const subTrigger = document.querySelector<HTMLElement>(
1046 '.tsqd-settings-menu-sub-trigger-position',
1048 expect(subTrigger).not.toBeNull()
1049 fireEvent.keyDown(subTrigger!, { key: 'ArrowRight' })
1050 expect(
1051 document.querySelector('[aria-label="Position settings"]'),
1052 ).not.toBeNull()
1053 })
1054​
1055 it('should persist "position" when a position radio item is selected', () => {
1056 const rendered = renderDevtools({ initialIsOpen: true })
1057​
1058 fireEvent.keyDown(rendered.getByLabelText('Open settings menu'), {
1059 key: 'Enter',
1060 })
1061​
1062 const subTrigger = document.querySelector<HTMLElement>(
1063 '.tsqd-settings-menu-sub-trigger-position',
1065 expect(subTrigger).not.toBeNull()
1066 fireEvent.keyDown(subTrigger!, { key: 'ArrowRight' })
1067​
1068 const topItem = document.querySelector<HTMLElement>(
1069 '.tsqd-settings-menu-position-btn-top',
1071 expect(topItem).not.toBeNull()
1072 fireEvent.keyDown(topItem!, { key: 'Enter' })
1073 expect(localStorage.getItem('TanstackQueryDevtools.position')).toBe('top')
1074 })
1075​
1076 it('should open "Theme" sub-menu when the sub-trigger is activated', () => {
1077 const rendered = renderDevtools({ initialIsOpen: true })
1078​
1079 fireEvent.keyDown(rendered.getByLabelText('Open settings menu'), {
1080 key: 'Enter',
1081 })
1082​
1083 const themeTrigger = document.querySelector<HTMLElement>(
1084 '.tsqd-settings-menu-sub-trigger-theme',
1086 expect(themeTrigger).not.toBeNull()
1087 expect(themeTrigger).not.toBe(
1088 document.querySelector('.tsqd-settings-menu-sub-trigger-position'),
1090 fireEvent.keyDown(themeTrigger!, { key: 'ArrowRight' })
1091 expect(
1092 document.querySelector('[aria-label="Theme preference"]'),
1093 ).not.toBeNull()
1094 })
1095​
1096 it('should persist "theme_preference" when a theme radio item is selected', () => {
1097 const rendered = renderDevtools({ initialIsOpen: true })
1098​
1099 fireEvent.keyDown(rendered.getByLabelText('Open settings menu'), {
1100 key: 'Enter',
1101 })
1102​
1103 const themeTrigger = document.querySelector<HTMLElement>(
1104 '.tsqd-settings-menu-sub-trigger-theme',
1106 expect(themeTrigger).not.toBeNull()
1107 fireEvent.keyDown(themeTrigger!, { key: 'ArrowRight' })
1108​
1109 const themeMenu = document.querySelector(
1110 '[aria-label="Theme preference"]',
1112 const lightItem = Array.from(
1113 themeMenu?.querySelectorAll<HTMLElement>('[role="menuitemradio"]') ??
1114 [],
1115 ).find((el) => String(el.textContent).includes('Light'))
1116 expect(lightItem).not.toBeUndefined()
1117 fireEvent.keyDown(lightItem!, { key: 'Enter' })
1118 expect(
1119 localStorage.getItem('TanstackQueryDevtools.theme_preference'),
1120 ).toBe('light')
1121 })
1122​
1123 it('should open "Hide disabled queries" sub-menu when the sub-trigger is activated', () => {
1124 const rendered = renderDevtools({ initialIsOpen: true })
1125​
1126 fireEvent.keyDown(rendered.getByLabelText('Open settings menu'), {
1127 key: 'Enter',
1128 })
1129​
1130 const hideTrigger = document.querySelector<HTMLElement>(
1131 '.tsqd-settings-menu-sub-trigger-disabled-queries',
1133 expect(hideTrigger).not.toBeNull()
1134 fireEvent.keyDown(hideTrigger!, { key: 'ArrowRight' })
1135 expect(
1136 document.querySelector('[aria-label="Hide disabled queries setting"]'),
1137 ).not.toBeNull()
1138 })
1139​
1140 it('should persist "hideDisabledQueries" when a hide-disabled radio item is selected', () => {
1141 const rendered = renderDevtools({ initialIsOpen: true })
1142​
1143 fireEvent.keyDown(rendered.getByLabelText('Open settings menu'), {
1144 key: 'Enter',
1145 })
1146​
1147 const hideTrigger = document.querySelector<HTMLElement>(
1148 '.tsqd-settings-menu-sub-trigger-disabled-queries',
1150 expect(hideTrigger).not.toBeNull()
1151 fireEvent.keyDown(hideTrigger!, { key: 'ArrowRight' })
1152​
1153 const hideItem = document.querySelector<HTMLElement>(
1154 '.tsqd-settings-menu-position-btn-hide',
1156 expect(hideItem).not.toBeNull()
1157 fireEvent.keyDown(hideItem!, { key: 'Enter' })
1158 expect(
1159 localStorage.getItem('TanstackQueryDevtools.hideDisabledQueries'),
1160 ).toBe('true')
1161 })
1162 })
1163​
1164 describe('resize handle', () => {
1165 it('should increase height when "ArrowUp" is pressed on the resize handle in "bottom" position', () => {
1166 const rendered = renderDevtools(
1167 { position: 'bottom', initialIsOpen: true },
1168 { 'TanstackQueryDevtools.height': '500' },
1170​
1171 const handle = rendered.getByLabelText('Resize devtools panel')
1172 fireEvent.keyDown(handle, { key: 'ArrowUp' })
1173 expect(
1174 Number(localStorage.getItem('TanstackQueryDevtools.height')),
1175 ).toBeGreaterThan(500)
1176 })
1177​
1178 it('should decrease height when "ArrowDown" is pressed on the resize handle in "bottom" position', () => {
1179 const rendered = renderDevtools(
1180 { position: 'bottom', initialIsOpen: true },
1181 { 'TanstackQueryDevtools.height': '500' },
1183​
1184 const handle = rendered.getByLabelText('Resize devtools panel')
1185 fireEvent.keyDown(handle, { key: 'ArrowDown' })
1186​
1187 // Assert the value exists before parsing β€” `Number(null)` is `0`,
1188 // which would falsely satisfy `toBeLessThan(500)` if the write was missing.
1189 const nextHeight = localStorage.getItem('TanstackQueryDevtools.height')
1190 expect(nextHeight).not.toBeNull()
1191 expect(Number(nextHeight)).toBeLessThan(500)
1192 })
1193​
1194 it('should increase width when "ArrowLeft" is pressed on the resize handle in "right" position', () => {
1195 const rendered = renderDevtools(
1196 { position: 'right', initialIsOpen: true },
1197 { 'TanstackQueryDevtools.width': '500' },
1199​
1200 const handle = rendered.getByLabelText('Resize devtools panel')
1201 fireEvent.keyDown(handle, { key: 'ArrowLeft' })
1202 expect(
1203 Number(localStorage.getItem('TanstackQueryDevtools.width')),
1204 ).toBeGreaterThan(500)
1205 })
1206​
1207 it('should decrease width when "ArrowRight" is pressed on the resize handle in "right" position', () => {
1208 const rendered = renderDevtools(
1209 { position: 'right', initialIsOpen: true },
1210 { 'TanstackQueryDevtools.width': '500' },
1212​
1213 const handle = rendered.getByLabelText('Resize devtools panel')
1214 fireEvent.keyDown(handle, { key: 'ArrowRight' })
1215​
1216 const nextWidth = localStorage.getItem('TanstackQueryDevtools.width')
1217 expect(nextWidth).not.toBeNull()
1218 expect(Number(nextWidth)).toBeLessThan(500)
1219 })
1220​
1221 it('should increase height while dragging up in "bottom" position', () => {
1222 const initialHeight = 500
1223 const rendered = renderDevtools(
1224 { position: 'bottom', initialIsOpen: true },
1225 { 'TanstackQueryDevtools.height': String(initialHeight) },
1227​
1228 const handle = rendered.getByLabelText('Resize devtools panel')
1229 // jsdom returns zeros for `getBoundingClientRect`; stub the panel size so
1230 // that drag math starts from `initialHeight` instead of 0.
1231 // Only `height` is read by the production code; other fields are unused.
1232 const panel = handle.parentElement
1233 expect(panel).toBeInstanceOf(HTMLElement)
1234 vi.spyOn(panel!, 'getBoundingClientRect').mockReturnValue({
1235 height: initialHeight,
1236 width: 0,
1237 x: 0,
1238 y: 0,
1239 top: 0,
1240 right: 0,
1241 bottom: 0,
1242 left: 0,
1243 toJSON: () => ({}),
1244 })
1245​
1246 // Move the cursor up by 50px (`clientY` 100 β†’ 50), which adds 50px to the
1247 // drag base of `initialHeight`.
1248 fireEvent.mouseDown(handle, { clientX: 0, clientY: 100 })
1249 fireEvent(
1250 document,
1251 new MouseEvent('mousemove', { clientX: 0, clientY: 50 }),
1253 fireEvent(document, new MouseEvent('mouseup'))
1254 expect(
1255 Number(localStorage.getItem('TanstackQueryDevtools.height')),
1256 ).toBeGreaterThan(initialHeight)
1257 })
1258​
1259 it('should increase width while dragging left in "right" position', () => {
1260 const initialWidth = 500
1261 const rendered = renderDevtools(
1262 { position: 'right', initialIsOpen: true },
1263 { 'TanstackQueryDevtools.width': String(initialWidth) },
1265​
1266 const handle = rendered.getByLabelText('Resize devtools panel')
1267 // `width` is read twice during drag: once as the base size, and again to
1268 // detect when the panel hits its minimum. Returning the same value both
1269 // times keeps the "minimum reached" branch from firing.
1270 const panel = handle.parentElement
1271 expect(panel).toBeInstanceOf(HTMLElement)
1272 vi.spyOn(panel!, 'getBoundingClientRect').mockReturnValue({
1273 height: 0,
1274 width: initialWidth,
1275 x: 0,
1276 y: 0,
1277 top: 0,
1278 right: 0,
1279 bottom: 0,
1280 left: 0,
1281 toJSON: () => ({}),
1282 })
1283​
1284 // Move the cursor left by 50px (`clientX` 100 β†’ 50); in `right` position,
1285 // moving left grows the panel by 50px from the drag base of `initialWidth`.
1286 fireEvent.mouseDown(handle, { clientX: 100, clientY: 0 })
1287 fireEvent(
1288 document,
1289 new MouseEvent('mousemove', { clientX: 50, clientY: 0 }),
1291 fireEvent(document, new MouseEvent('mouseup'))
1292 expect(
1293 Number(localStorage.getItem('TanstackQueryDevtools.width')),
1294 ).toBeGreaterThan(initialWidth)
1295 })
1296​
1297 it('should clamp the width to the minimum when dragging shrinks the panel below the minimum width', () => {
1298 const initialWidth = 200
1299 const rendered = renderDevtools(
1300 { position: 'left', initialIsOpen: true },
1301 { 'TanstackQueryDevtools.width': String(initialWidth) },
1303​
1304 const handle = rendered.getByLabelText('Resize devtools panel')
1305 const panel = handle.parentElement
1306 expect(panel).toBeInstanceOf(HTMLElement)
1307 // `width` is read twice during drag: once as the base size, and again
1308 // after the clamp to detect when the panel has hit its minimum. The
1309 // first call returns `initialWidth`; the second returns `0` so the
1310 // `localStore.width < newWidth` restore branch stays inactive and only
1311 // the `newSize < minWidth` clamp is observed.
1312 const getBoundingClientRect = vi
1313 .spyOn(panel!, 'getBoundingClientRect')
1314 .mockReturnValueOnce({
1315 height: 0,
1316 width: initialWidth,
1317 x: 0,
1318 y: 0,
1319 top: 0,
1320 right: 0,
1321 bottom: 0,
1322 left: 0,
1323 toJSON: () => ({}),
1324 })
1325 getBoundingClientRect.mockReturnValue({
1326 height: 0,
1327 width: 0,
1328 x: 0,
1329 y: 0,
1330 top: 0,
1331 right: 0,
1332 bottom: 0,
1333 left: 0,
1334 toJSON: () => ({}),
1335 })
1336​
1337 // In `left` position, dragging the cursor left (`clientX` 100 β†’ 0)
1338 // shrinks the panel by 100px, which lands well under the 192px minimum.
1339 fireEvent.mouseDown(handle, { clientX: 100, clientY: 0 })
1340 fireEvent(
1341 document,
1342 new MouseEvent('mousemove', { clientX: 0, clientY: 0 }),
1344 fireEvent(document, new MouseEvent('mouseup'))
1345 expect(Number(localStorage.getItem('TanstackQueryDevtools.width'))).toBe(
1346 192,
1348 })
1349​
1350 it('should restore "width" to the rendered minimum when the panel is dragged below its content width', () => {
1351 const initialWidth = 400
1352 // The panel uses `min-width: min-content`, so the rendered width may
1353 // exceed the 192px `minWidth` constant when its children are wider; any
1354 // value > 192 here triggers the `localStore.width < newWidth` restore
1355 // branch.
1356 const renderedMinWidth = 250
1357 const rendered = renderDevtools(
1358 { position: 'left', initialIsOpen: true },
1359 { 'TanstackQueryDevtools.width': String(initialWidth) },
1361​
1362 const handle = rendered.getByLabelText('Resize devtools panel')
1363 const panel = handle.parentElement
1364 expect(panel).toBeInstanceOf(HTMLElement)
1365 const getBoundingClientRect = vi
1366 .spyOn(panel!, 'getBoundingClientRect')
1367 .mockReturnValueOnce({
1368 height: 0,
1369 width: initialWidth,
1370 x: 0,
1371 y: 0,
1372 top: 0,
1373 right: 0,
1374 bottom: 0,
1375 left: 0,
1376 toJSON: () => ({}),
1377 })
1378 getBoundingClientRect.mockReturnValue({
1379 height: 0,
1380 width: renderedMinWidth,
1381 x: 0,
1382 y: 0,
1383 top: 0,
1384 right: 0,
1385 bottom: 0,
1386 left: 0,
1387 toJSON: () => ({}),
1388 })
1389​
1390 // Drag 300px left shrinks the panel to 100 β€” below `minWidth`, so the
1391 // clamp + restore branches both fire.
1392 fireEvent.mouseDown(handle, { clientX: 300, clientY: 0 })
1393 fireEvent(
1394 document,
1395 new MouseEvent('mousemove', { clientX: 0, clientY: 0 }),
1397 fireEvent(document, new MouseEvent('mouseup'))
1398 expect(Number(localStorage.getItem('TanstackQueryDevtools.width'))).toBe(
1399 renderedMinWidth,
1401 })
1402​
1403 it('should close the query details panel when dragging shrinks the panel below the minimum height', () => {
1404 queryClient.setQueryData(['shrink-below-min-height'], [{ id: 1 }])
1405 const rendered = renderDevtools({
1406 position: 'bottom',
1407 initialIsOpen: true,
1408 })
1409​
1410 // Open the query details so `selectedQueryHash` is set.
1411 fireEvent.click(
1412 rendered.getByLabelText(/Query key \["shrink-below-min-height"\]/),
1414 expect(rendered.getByText('Query Details')).toBeInTheDocument()
1415​
1416 const handle = rendered.getByLabelText('Resize devtools panel')
1417 const panel = handle.parentElement
1418 expect(panel).toBeInstanceOf(HTMLElement)
1419 // Stub the base size to a value just above the 56px (`3.5rem`) minimum so
1420 // a small downward drag pushes `newSize` below `minHeight` and triggers
1421 // the clamp branch that also resets `selectedQueryHash`.
1422 vi.spyOn(panel!, 'getBoundingClientRect').mockReturnValue({
1423 height: 60,
1424 width: 0,
1425 x: 0,
1426 y: 0,
1427 top: 0,
1428 right: 0,
1429 bottom: 0,
1430 left: 0,
1431 toJSON: () => ({}),
1432 })
1433​
1434 // In `bottom` position, dragging the cursor down (`clientY` 100 β†’ 200)
1435 // shrinks the panel by 100px, which is well under the 56px minimum.
1436 fireEvent.mouseDown(handle, { clientX: 0, clientY: 100 })
1437 fireEvent(
1438 document,
1439 new MouseEvent('mousemove', { clientX: 0, clientY: 200 }),
1441 fireEvent(document, new MouseEvent('mouseup'))
1442 expect(rendered.queryByText('Query Details')).not.toBeInTheDocument()
1443 })
1444 })
1445​
1446 describe('online toggle', () => {
1447 it('should swap the toggle label after the offline button is clicked', () => {
1448 const rendered = renderDevtools({ initialIsOpen: true })
1449​
1450 fireEvent.click(rendered.getByLabelText('Mock offline behavior'))
1451 expect(
1452 rendered.getByLabelText('Unset offline mocking behavior'),
1453 ).toBeInTheDocument()
1454 })
1455 })
1456​
1457 describe('logo close', () => {
1458 it('should hide the panel when the TanStack logo is clicked', () => {
1459 const rendered = renderDevtools({ initialIsOpen: true })
1460​
1461 fireEvent.click(rendered.getByLabelText('Close Tanstack query devtools'))
1462 expect(
1463 rendered.queryByLabelText('Tanstack query devtools'),
1464 ).not.toBeInTheDocument()
1465 })
1466 })