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

Explorer.test.tsx

664 lines22.3 KB

1import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
2import { fireEvent, render, within } from '@solidjs/testing-library'
3import { QueryClient, onlineManager } from '@tanstack/query-core'
4import Explorer from '../Explorer'
5import { QueryDevtoolsContext, ThemeContext } from '../contexts'
6import type { Query } from '@tanstack/query-core'
7​
8// `goober` compiles every `css\`...\`` template literal at mount time;
9// replace it with a no-op factory so label/role-based assertions stay fast.
10vi.mock(import('goober'), () => {
11 let counter = 0
12 const css = Object.assign(() => `tsqd-${++counter}`, {
13 bind: () => css,
14 })
15 return { css, glob: () => {}, setup: () => {} }
16})
17​
18describe('Explorer', () => {
19 let queryClient: QueryClient
20​
21 beforeEach(() => {
22 vi.useFakeTimers()
23 queryClient = new QueryClient()
24 })
25​
26 afterEach(() => {
27 queryClient.clear()
28 vi.useRealTimers()
29 })
30​
31 function renderExplorer(
32 props: Parameters<typeof Explorer>[0],
33 options: { theme?: 'dark' | 'light' } = {},
34 ) {
35 const theme = options.theme ?? 'dark'
36 return render(() => (
37 <QueryDevtoolsContext.Provider
38 value={{
39 client: queryClient,
40 queryFlavor: 'TanStack Query',
41 version: '5',
42 onlineManager,
43 }}
44 >
45 <ThemeContext.Provider value={() => theme}>
46 <Explorer {...props} />
47 </ThemeContext.Provider>
48 </QueryDevtoolsContext.Provider>
49 ))
50 }
51​
52 describe('primitive values', () => {
53 it('should render a "label: value" row for a string value', () => {
54 const rendered = renderExplorer({ label: 'name', value: 'Anna' })
55​
56 expect(rendered.getByText('name:')).toBeInTheDocument()
57 expect(rendered.getByText('"Anna"')).toBeInTheDocument()
58 })
59​
60 it('should render a "label: value" row for a number value', () => {
61 const rendered = renderExplorer({ label: 'count', value: 42 })
62​
63 expect(rendered.getByText('count:')).toBeInTheDocument()
64 expect(rendered.getByText('42')).toBeInTheDocument()
65 })
66​
67 it('should render a "label: value" row for a boolean value', () => {
68 const rendered = renderExplorer({ label: 'active', value: true })
69​
70 expect(rendered.getByText('active:')).toBeInTheDocument()
71 expect(rendered.getByText('true')).toBeInTheDocument()
72 })
73​
74 it('should render a "label: value" row for a "null" value', () => {
75 const rendered = renderExplorer({ label: 'missing', value: null })
76​
77 expect(rendered.getByText('missing:')).toBeInTheDocument()
78 expect(rendered.getByText('null')).toBeInTheDocument()
79 })
80 })
81​
82 describe('arrays and objects', () => {
83 it('should render an empty object as a primitive row (no expander)', () => {
84 const rendered = renderExplorer({ label: 'data', value: {} })
85​
86 expect(rendered.getByText('data:')).toBeInTheDocument()
87 expect(
88 rendered.queryByRole('button', { expanded: false }),
89 ).not.toBeInTheDocument()
90 })
91​
92 it('should render an array with an expander showing the item count', () => {
93 const rendered = renderExplorer({
94 label: 'list',
95 value: ['a', 'b', 'c'],
96 })
97​
98 const expander = rendered.getByRole('button', { expanded: false })
99 expect(expander).toBeInTheDocument()
100 expect(expander).toHaveTextContent('list')
101 expect(expander).toHaveTextContent('3 items')
102 })
103​
104 it('should render children under their index labels when the array expander is clicked', () => {
105 const rendered = renderExplorer({
106 label: 'list',
107 value: ['a', 'b'],
108 })
109​
110 fireEvent.click(rendered.getByRole('button', { expanded: false }))
111 expect(rendered.getByText('0:')).toBeInTheDocument()
112 expect(rendered.getByText('1:')).toBeInTheDocument()
113 expect(rendered.getByText('"a"')).toBeInTheDocument()
114 expect(rendered.getByText('"b"')).toBeInTheDocument()
115 })
116​
117 it('should render object entries under their keys when expanded', () => {
118 const rendered = renderExplorer({
119 label: 'user',
120 value: { name: 'Anna', age: 30 },
121 })
122​
123 fireEvent.click(rendered.getByRole('button', { expanded: false }))
124 expect(rendered.getByText('name:')).toBeInTheDocument()
125 expect(rendered.getByText('"Anna"')).toBeInTheDocument()
126 expect(rendered.getByText('age:')).toBeInTheDocument()
127 expect(rendered.getByText('30')).toBeInTheDocument()
128 })
129 })
130​
131 describe('Map and iterable values', () => {
132 it('should preserve "Map" keys as labels when expanded', () => {
133 const rendered = renderExplorer({
134 label: 'm',
135 value: new Map([
136 ['first', 1],
137 ['second', 2],
138 ]),
139 })
140​
141 fireEvent.click(rendered.getByRole('button', { expanded: false }))
142 expect(rendered.getByText('first:')).toBeInTheDocument()
143 expect(rendered.getByText('second:')).toBeInTheDocument()
144 })
145​
146 it('should mark an iterable value with an "(Iterable)" prefix on the expander', () => {
147 const rendered = renderExplorer({
148 label: 's',
149 value: new Set(['x', 'y']),
150 })
151​
152 expect(
153 rendered.getByRole('button', { expanded: false }),
154 ).toHaveTextContent('(Iterable)')
155 })
156​
157 it('should render iterable children under their numeric index when expanded', () => {
158 const rendered = renderExplorer({
159 label: 's',
160 value: new Set(['x', 'y']),
161 })
162​
163 fireEvent.click(rendered.getByRole('button', { expanded: false }))
164 expect(rendered.getByText('0:')).toBeInTheDocument()
165 expect(rendered.getByText('1:')).toBeInTheDocument()
166 })
167 })
168​
169 describe('"defaultExpanded"', () => {
170 it('should render children eagerly when the label is in "defaultExpanded"', () => {
171 const rendered = renderExplorer({
172 label: 'list',
173 value: ['a'],
174 defaultExpanded: ['list'],
175 })
176​
177 expect(
178 rendered.getByRole('button', { expanded: true }),
179 ).toBeInTheDocument()
180 expect(rendered.getByText('0:')).toBeInTheDocument()
181 })
182 })
183​
184 describe('action menu', () => {
185 it('should copy the serialized value to the clipboard when the copy button is clicked', () => {
186 const writeText = vi
187 .fn<Clipboard['writeText']>()
188 .mockResolvedValue(undefined)
189 vi.stubGlobal('navigator', { clipboard: { writeText } })
190 queryClient.setQueryData(['data'], { name: 'Anna' })
191​
192 const rendered = renderExplorer({
193 label: 'data',
194 value: { name: 'Anna' },
195 editable: true,
196 // oxlint-disable-next-line typescript/no-unnecessary-type-assertion
197 activeQuery: queryClient
198 .getQueryCache()
199 .find({ queryKey: ['data'] }) as Query,
200 })
201​
202 fireEvent.click(rendered.getByLabelText('Copy object to clipboard'))
203 expect(writeText).toHaveBeenCalledTimes(1)
204 const [arg] = writeText.mock.calls[0]!
205 expect(JSON.parse(arg)).toMatchObject({
206 json: { name: 'Anna' },
207 })
208 })
209​
210 it('should switch the copy button to an error state when clipboard write fails', async () => {
211 const writeText = vi
212 .fn<Clipboard['writeText']>()
213 .mockRejectedValue(new Error('denied'))
214 vi.stubGlobal('navigator', { clipboard: { writeText } })
215 const consoleErrorMock = vi
216 .spyOn(console, 'error')
217 .mockImplementation(() => {})
218 queryClient.setQueryData(['data'], { name: 'Anna' })
219​
220 const rendered = renderExplorer({
221 label: 'data',
222 value: { name: 'Anna' },
223 editable: true,
224 // oxlint-disable-next-line typescript/no-unnecessary-type-assertion
225 activeQuery: queryClient
226 .getQueryCache()
227 .find({ queryKey: ['data'] }) as Query,
228 })
229​
230 fireEvent.click(rendered.getByLabelText('Copy object to clipboard'))
231 await vi.advanceTimersByTimeAsync(0)
232 expect(
233 rendered.getByLabelText('Error copying object to clipboard'),
234 ).toBeInTheDocument()
235 expect(consoleErrorMock).toHaveBeenCalledWith(
236 'Failed to copy: ',
237 new Error('denied'),
238 )
239 })
240​
241 it('should reset the copy button to the idle state 1500ms after a successful copy', async () => {
242 const writeText = vi
243 .fn<Clipboard['writeText']>()
244 .mockResolvedValue(undefined)
245 vi.stubGlobal('navigator', { clipboard: { writeText } })
246 queryClient.setQueryData(['data'], { name: 'Anna' })
247​
248 const rendered = renderExplorer({
249 label: 'data',
250 value: { name: 'Anna' },
251 editable: true,
252 // oxlint-disable-next-line typescript/no-unnecessary-type-assertion
253 activeQuery: queryClient
254 .getQueryCache()
255 .find({ queryKey: ['data'] }) as Query,
256 })
257​
258 fireEvent.click(rendered.getByLabelText('Copy object to clipboard'))
259 await vi.advanceTimersByTimeAsync(0)
260 expect(
261 rendered.getByLabelText('Object copied to clipboard'),
262 ).toBeInTheDocument()
263 await vi.advanceTimersByTimeAsync(1500)
264 expect(
265 rendered.getByLabelText('Copy object to clipboard'),
266 ).toBeInTheDocument()
267 })
268​
269 it('should reset the copy button to the idle state 1500ms after a failed copy', async () => {
270 const writeText = vi
271 .fn<Clipboard['writeText']>()
272 .mockRejectedValue(new Error('denied'))
273 vi.stubGlobal('navigator', { clipboard: { writeText } })
274 vi.spyOn(console, 'error').mockImplementation(() => {})
275 queryClient.setQueryData(['data'], { name: 'Anna' })
276​
277 const rendered = renderExplorer({
278 label: 'data',
279 value: { name: 'Anna' },
280 editable: true,
281 // oxlint-disable-next-line typescript/no-unnecessary-type-assertion
282 activeQuery: queryClient
283 .getQueryCache()
284 .find({ queryKey: ['data'] }) as Query,
285 })
286​
287 fireEvent.click(rendered.getByLabelText('Copy object to clipboard'))
288 await vi.advanceTimersByTimeAsync(0)
289 expect(
290 rendered.getByLabelText('Error copying object to clipboard'),
291 ).toBeInTheDocument()
292 await vi.advanceTimersByTimeAsync(1500)
293 expect(
294 rendered.getByLabelText('Copy object to clipboard'),
295 ).toBeInTheDocument()
296 })
297​
298 it('should clear array items via "setQueryData" when the clear-array button is clicked', () => {
299 queryClient.setQueryData(['data'], ['a', 'b', 'c'])
300​
301 const rendered = renderExplorer({
302 label: 'list',
303 value: ['a', 'b', 'c'],
304 editable: true,
305 // oxlint-disable-next-line typescript/no-unnecessary-type-assertion
306 activeQuery: queryClient
307 .getQueryCache()
308 .find({ queryKey: ['data'] }) as Query,
309 })
310​
311 fireEvent.click(rendered.getByLabelText('Remove all items'))
312 expect(queryClient.getQueryData(['data'])).toStrictEqual([])
313 })
314​
315 it('should delete the entry at the current "dataPath" when the delete button is clicked', () => {
316 queryClient.setQueryData(['data'], ['a', 'b', 'c'])
317​
318 const rendered = renderExplorer({
319 label: 'list',
320 value: ['a', 'b', 'c'],
321 editable: true,
322 itemsDeletable: true,
323 // oxlint-disable-next-line typescript/no-unnecessary-type-assertion
324 activeQuery: queryClient
325 .getQueryCache()
326 .find({ queryKey: ['data'] }) as Query,
327 dataPath: ['1'],
328 })
329​
330 fireEvent.click(rendered.getByLabelText('Delete item'))
331 expect(queryClient.getQueryData(['data'])).toStrictEqual(['a', 'c'])
332 })
333​
334 it('should toggle a boolean value via "setQueryData" when the toggle button is clicked', () => {
335 queryClient.setQueryData(['data'], { flag: true })
336​
337 const rendered = renderExplorer({
338 label: 'flag',
339 value: true,
340 editable: true,
341 // oxlint-disable-next-line typescript/no-unnecessary-type-assertion
342 activeQuery: queryClient
343 .getQueryCache()
344 .find({ queryKey: ['data'] }) as Query,
345 dataPath: ['flag'],
346 })
347​
348 fireEvent.click(rendered.getByLabelText('Toggle value'))
349 expect(queryClient.getQueryData(['data'])).toStrictEqual({ flag: false })
350 })
351​
352 it.each([true, false])(
353 'should expose "aria-pressed" on the toggle button when the value is %s',
354 (value) => {
355 queryClient.setQueryData(['data'], { flag: value })
356​
357 const rendered = renderExplorer({
358 label: 'flag',
359 value,
360 editable: true,
361 // oxlint-disable-next-line typescript/no-unnecessary-type-assertion
362 activeQuery: queryClient
363 .getQueryCache()
364 .find({ queryKey: ['data'] }) as Query,
365 dataPath: ['flag'],
366 })
367​
368 expect(rendered.getByLabelText('Toggle value')).toHaveAttribute(
369 'aria-pressed',
370 String(value),
371 )
372 },
373 )
374​
375 it('should not render action buttons when "editable" is false', () => {
376 queryClient.setQueryData(['data'], ['a'])
377​
378 const rendered = renderExplorer({
379 label: 'list',
380 value: ['a'],
381 editable: false,
382 // oxlint-disable-next-line typescript/no-unnecessary-type-assertion
383 activeQuery: queryClient
384 .getQueryCache()
385 .find({ queryKey: ['data'] }) as Query,
386 })
387​
388 expect(
389 rendered.queryByLabelText('Copy object to clipboard'),
390 ).not.toBeInTheDocument()
391 expect(
392 rendered.queryByLabelText('Remove all items'),
393 ).not.toBeInTheDocument()
394 })
395​
396 it('should not render "ClearArrayButton" when value is not an array', () => {
397 queryClient.setQueryData(['data'], { name: 'Anna' })
398​
399 const rendered = renderExplorer({
400 label: 'user',
401 value: { name: 'Anna' },
402 editable: true,
403 // oxlint-disable-next-line typescript/no-unnecessary-type-assertion
404 activeQuery: queryClient
405 .getQueryCache()
406 .find({ queryKey: ['data'] }) as Query,
407 })
408​
409 expect(
410 rendered.queryByLabelText('Remove all items'),
411 ).not.toBeInTheDocument()
412 expect(
413 rendered.getByLabelText('Copy object to clipboard'),
414 ).toBeInTheDocument()
415 })
416 })
417​
418 describe('pagination', () => {
419 it('should group entries into 100-item pages when the array has more than 100 entries', () => {
420 const rendered = renderExplorer({
421 label: 'big',
422 value: Array.from({ length: 101 }, (_, i) => i),
423 })
424​
425 fireEvent.click(rendered.getByRole('button', { expanded: false }))
426 expect(rendered.getByText('[0...99]')).toBeInTheDocument()
427 expect(rendered.getByText('[100...199]')).toBeInTheDocument()
428 })
429​
430 it('should keep the items of a page hidden until the page header is clicked', () => {
431 const rendered = renderExplorer({
432 label: 'big',
433 value: Array.from({ length: 101 }, (_, i) => `item-${i}`),
434 })
435​
436 fireEvent.click(rendered.getByRole('button', { expanded: false }))
437 expect(rendered.queryByText('0:')).not.toBeInTheDocument()
438 })
439​
440 it('should reveal the items of a page when the page header is clicked', () => {
441 const rendered = renderExplorer({
442 label: 'big',
443 value: Array.from({ length: 101 }, (_, i) => `item-${i}`),
444 })
445​
446 fireEvent.click(rendered.getByRole('button', { expanded: false }))
447 fireEvent.click(rendered.getByText('[0...99]'))
448 expect(rendered.getByText('0:')).toBeInTheDocument()
449 expect(rendered.getByText('"item-0"')).toBeInTheDocument()
450 })
451​
452 it('should independently toggle two pages when their headers are clicked', () => {
453 const rendered = renderExplorer({
454 label: 'big',
455 value: Array.from({ length: 200 }, (_, i) => `item-${i}`),
456 })
457​
458 fireEvent.click(rendered.getByRole('button', { expanded: false }))
459 fireEvent.click(rendered.getByText('[0...99]'))
460 fireEvent.click(rendered.getByText('[100...199]'))
461 expect(rendered.getByText('"item-0"')).toBeInTheDocument()
462 expect(rendered.getByText('"item-100"')).toBeInTheDocument()
463​
464 fireEvent.click(rendered.getByText('[0...99]'))
465 expect(rendered.queryByText('"item-0"')).not.toBeInTheDocument()
466 expect(rendered.getByText('"item-100"')).toBeInTheDocument()
467 })
468​
469 it('should render action buttons for items inside a paginated page', () => {
470 const value: Array<Array<number>> = Array.from(
471 { length: 200 },
472 (_, i) => [i],
473 )
474 queryClient.setQueryData(['data'], value)
475​
476 const rendered = renderExplorer({
477 label: 'Data',
478 value,
479 defaultExpanded: ['Data'],
480 editable: true,
481 // oxlint-disable-next-line typescript/no-unnecessary-type-assertion
482 activeQuery: queryClient
483 .getQueryCache()
484 .find({ queryKey: ['data'] }) as Query,
485 })
486​
487 fireEvent.click(rendered.getByText('[0...99]'))
488 expect(
489 rendered.getAllByLabelText('Remove all items').length,
490 ).toBeGreaterThan(1)
491 })
492 })
493​
494 describe('inline edit', () => {
495 it('should write the new string value via "setQueryData" when a text input is changed', () => {
496 queryClient.setQueryData(['data'], { name: 'Anna' })
497​
498 const rendered = renderExplorer({
499 label: 'name',
500 value: 'Anna',
501 editable: true,
502 // oxlint-disable-next-line typescript/no-unnecessary-type-assertion
503 activeQuery: queryClient
504 .getQueryCache()
505 .find({ queryKey: ['data'] }) as Query,
506 dataPath: ['name'],
507 })
508​
509 const input = rendered.getByLabelText('name:')
510 expect(input).toHaveAttribute('type', 'text')
511​
512 fireEvent.change(input, { target: { value: 'Bob' } })
513 expect(queryClient.getQueryData(['data'])).toStrictEqual({ name: 'Bob' })
514 })
515​
516 it('should write the new number value via "setQueryData" when a number input is changed', () => {
517 queryClient.setQueryData(['data'], { count: 1 })
518​
519 const rendered = renderExplorer({
520 label: 'count',
521 value: 1,
522 editable: true,
523 // oxlint-disable-next-line typescript/no-unnecessary-type-assertion
524 activeQuery: queryClient
525 .getQueryCache()
526 .find({ queryKey: ['data'] }) as Query,
527 dataPath: ['count'],
528 })
529​
530 const input = rendered.getByLabelText('count:')
531 expect(input).toHaveAttribute('type', 'number')
532​
533 fireEvent.change(input, {
534 target: { value: '42', valueAsNumber: 42 },
535 })
536 expect(queryClient.getQueryData(['data'])).toStrictEqual({ count: 42 })
537 })
538​
539 it('should render "ToggleValueButton" inline for a boolean primitive row', () => {
540 queryClient.setQueryData(['data'], { flag: false })
541​
542 const rendered = renderExplorer({
543 label: 'flag',
544 value: false,
545 editable: true,
546 // oxlint-disable-next-line typescript/no-unnecessary-type-assertion
547 activeQuery: queryClient
548 .getQueryCache()
549 .find({ queryKey: ['data'] }) as Query,
550 dataPath: ['flag'],
551 })
552​
553 expect(rendered.getByLabelText('Toggle value')).toBeInTheDocument()
554 })
555​
556 it('should render "DeleteItemButton" inline when a primitive row has "itemsDeletable"', () => {
557 queryClient.setQueryData(['data'], { name: 'Anna' })
558​
559 const rendered = renderExplorer({
560 label: 'name',
561 value: 'Anna',
562 editable: true,
563 itemsDeletable: true,
564 // oxlint-disable-next-line typescript/no-unnecessary-type-assertion
565 activeQuery: queryClient
566 .getQueryCache()
567 .find({ queryKey: ['data'] }) as Query,
568 dataPath: ['name'],
569 })
570​
571 expect(rendered.getByLabelText('Delete item')).toBeInTheDocument()
572 })
573​
574 it('should delete fields from the active query when their inline delete buttons are clicked', () => {
575 const value = { name: 'Anna', age: 30 }
576 queryClient.setQueryData(['data'], value)
577​
578 const rendered = renderExplorer({
579 label: 'Data',
580 value,
581 defaultExpanded: ['Data'],
582 editable: true,
583 // oxlint-disable-next-line typescript/no-unnecessary-type-assertion
584 activeQuery: queryClient
585 .getQueryCache()
586 .find({ queryKey: ['data'] }) as Query,
587 })
588​
589 const ageRow = rendered.getByText('age:').parentElement!
590 fireEvent.click(within(ageRow).getByLabelText('Delete item'))
591 expect(queryClient.getQueryData(['data'])).toStrictEqual({ name: 'Anna' })
592​
593 const nameRow = rendered.getByText('name:').parentElement!
594 fireEvent.click(within(nameRow).getByLabelText('Delete item'))
595 expect(queryClient.getQueryData(['data'])).toStrictEqual({})
596 })
597 })
598​
599 describe('theme', () => {
600 it('should render without throwing under the "light" theme', () => {
601 const value = { items: ['a'], flag: true }
602 queryClient.setQueryData(['data'], value)
603​
604 expect(() =>
605 renderExplorer(
606 {
607 label: 'Data',
608 value,
609 defaultExpanded: ['Data'],
610 editable: true,
611 // oxlint-disable-next-line typescript/no-unnecessary-type-assertion
612 activeQuery: queryClient
613 .getQueryCache()
614 .find({ queryKey: ['data'] }) as Query,
615 },
616 { theme: 'light' },
617 ),
618 ).not.toThrow()
619 })
620 })
621​
622 describe('"shadowDOMTarget"', () => {
623 it('should render without throwing when a "shadowDOMTarget" is provided', () => {
624 const host = document.createElement('div')
625 document.body.appendChild(host)
626 const shadowRoot = host.attachShadow({ mode: 'open' })
627 const value = { items: ['a'], flag: true }
628 queryClient.setQueryData(['data'], value)
629​
630 try {
631 expect(() =>
632 render(() => (
633 <QueryDevtoolsContext.Provider
634 value={{
635 client: queryClient,
636 queryFlavor: 'TanStack Query',
637 version: '5',
638 onlineManager,
639 shadowDOMTarget: shadowRoot,
640 }}
641 >
642 <ThemeContext.Provider value={() => 'dark'}>
643 <Explorer
644 label="Data"
645 value={value}
646 defaultExpanded={['Data']}
647 editable={true}
648 activeQuery={
649 // oxlint-disable-next-line typescript/no-unnecessary-type-assertion
650 queryClient
651 .getQueryCache()
652 .find({ queryKey: ['data'] }) as Query
653 }
654 />
655 </ThemeContext.Provider>
656 </QueryDevtoolsContext.Provider>
657 )),
658 ).not.toThrow()
659 } finally {
660 host.remove()
661 }
662 })
663 })
664})