Open History to see the last commit
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})