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

Devtools.test.tsx

1,479 lines49.9 KB

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