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