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

Explorer.test.tsx

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