import { createLocalStorage } from '@solid-primitives/storage' import { cleanup, fireEvent, render, within } from '@solidjs/testing-library' import { QueryClient, QueryObserver, dehydrate, hydrate, noop, onlineManager, } from '@tanstack/query-core' import { createSignal } from 'solid-js' import { afterEach, assert, beforeEach, describe, expect, it, vi } from 'vitest' import { Devtools } from '../Devtools' import DevtoolsComponent from '../DevtoolsComponent' import DevtoolsPanelComponent from '../DevtoolsPanelComponent' import { PiPProvider, QueryDevtoolsContext, ThemeContext } from '../contexts' import { useDevtoolsState } from '../contexts/DevtoolsStateContext' import { DevtoolsOfflineProvider } from '../providers/DevtoolsOfflineProvider' import { DevtoolsStateProvider } from '../providers/DevtoolsStateProvider' import { DevtoolsSubscriptionsProvider } from '../providers/DevtoolsSubscriptionsProvider' import type { QueryDevtoolsProps } from '../contexts' // `solid-transition-group` internally imports from // `@solid-primitives/transition-group`, whose `exports` field points at // `src/index.ts` (not published) under a `@solid-primitives/source` condition // that Vite can't fall through, so we stub it with a transparent pass-through. vi.mock(import('solid-transition-group'), () => ({ TransitionGroup: (props) => props.children, })) describe('Devtools', () => { const storage: { [key: string]: string } = {} let queryClient: QueryClient let previousRootFontSize: string let resizeObservers: Array beforeEach(() => { resizeObservers = [] vi.useFakeTimers() previousRootFontSize = document.documentElement.style.fontSize vi.stubGlobal('localStorage', { getItem: (key: string) => Object.prototype.hasOwnProperty.call(storage, key) ? storage[key] : null, setItem: (key: string, value: string) => { storage[key] = value }, removeItem: (key: string) => { delete storage[key] }, clear: () => { Object.keys(storage).forEach((key) => delete storage[key]) }, }) vi.stubGlobal( 'matchMedia', vi.fn().mockImplementation((query: string) => ({ matches: false, media: query, onchange: null, addEventListener: vi.fn(), removeEventListener: vi.fn(), addListener: vi.fn(), removeListener: vi.fn(), dispatchEvent: vi.fn(), })), ) vi.stubGlobal( 'ResizeObserver', class { callback: ResizeObserverCallback constructor(callback: ResizeObserverCallback) { this.callback = callback resizeObservers.push(this) } observe = vi.fn<(target: Element) => void>((target: Element) => { this.callback( [ { target, contentRect: { width: 1000, height: 500 } as DOMRectReadOnly, } as ResizeObserverEntry, ], this, ) }) unobserve = vi.fn() disconnect = vi.fn() }, ) queryClient = new QueryClient() document.documentElement.style.fontSize = '16px' }) afterEach(() => { cleanup() Object.keys(storage).forEach((key) => delete storage[key]) queryClient.clear() onlineManager.setOnline(true) document.documentElement.style.fontSize = previousRootFontSize vi.useRealTimers() }) function renderDevtools( overrides: Partial = {}, initialStorage: Record = {}, onState?: (state: ReturnType) => void, ) { Object.entries(initialStorage).forEach(([key, value]) => { localStorage.setItem(key, value) }) function StateProbe() { onState?.(useDevtoolsState()) return null } return render(() => { const [localStore, setLocalStore] = createLocalStorage({ prefix: 'TanstackQueryDevtools', }) return ( 'dark'}> ) }) } it('should render only visible queries from a large cache', () => { for (let index = 0; index < 2000; index++) { queryClient.setQueryData(['large-cache', index], index) } const rendered = renderDevtools({ initialIsOpen: true }) const rows = rendered.getAllByRole('button', { name: /^Query key / }) expect(rows.length).toBeGreaterThan(0) expect(rows.length).toBeLessThan(100) }) describe('virtualized cache lists', () => { function getViewport( container: HTMLElement, view: 'queries' | 'mutations', ) { const viewport = container.querySelector( `.tsqd-${view}-overflow-container`, ) if (!viewport) throw new Error('Missing cache list viewport') return viewport } async function countStyleChanges( container: HTMLElement, action: () => void, ) { const content = getViewport(container, 'queries').firstElementChild assert(content) const records: Array = [] const observer = new MutationObserver((mutations) => { records.push(...mutations) }) observer.observe(content, { attributeFilter: ['style'] }) action() await vi.advanceTimersByTimeAsync(0) records.push(...observer.takeRecords()) observer.disconnect() return records.length } function seedQueries() { for (let index = 0; index < 1000; index++) { queryClient.setQueryData( [`query-${String(index).padStart(4, '0')}`], `data-${index}`, ) } } it('should keep selected query details updating when its row is offscreen', async () => { seedQueries() const rendered = renderDevtools( { initialIsOpen: true }, { 'TanstackQueryDevtools.sort': 'query hash' }, ) fireEvent.click(rendered.getByLabelText('Query key ["query-0000"]')) const viewport = getViewport(rendered.container, 'queries') viewport.scrollTo({ top: viewport.scrollHeight }) expect( rendered.queryByLabelText('Query key ["query-0000"]'), ).not.toBeInTheDocument() expect(rendered.getByLabelText('Query key ["query-0999"]')).toBeVisible() queryClient.setQueryData(['query-0000'], 'updated-selected-data') await vi.advanceTimersByTimeAsync(0) expect(rendered.getByDisplayValue('updated-selected-data')).toBeVisible() viewport.scrollTo({ top: 0 }) expect(rendered.getByLabelText('Query key ["query-0000"]')).toBeVisible() expect(rendered.getByText('Query Details')).toBeVisible() }) it('should filter, clear, and restore queries after distant scrolling', async () => { seedQueries() const rendered = renderDevtools({ initialIsOpen: true }) const viewport = getViewport(rendered.container, 'queries') viewport.scrollTo({ top: viewport.scrollHeight }) const filter = rendered.getByLabelText('Filter queries by query key') fireEvent.input(filter, { target: { value: 'query-0000' } }) viewport.scrollTo({ top: viewport.scrollTop }) expect(rendered.getAllByLabelText(/^Query key /)).toHaveLength(1) expect(rendered.getByLabelText('Query key ["query-0000"]')).toBeVisible() fireEvent.input(filter, { target: { value: 'no-query-matches' } }) expect(rendered.queryAllByLabelText(/^Query key /)).toHaveLength(0) fireEvent.input(filter, { target: { value: '' } }) expect(rendered.getAllByLabelText(/^Query key /).length).toBeLessThan(100) viewport.scrollTo({ top: viewport.scrollHeight }) fireEvent.click(rendered.getByLabelText('Clear query cache')) await vi.advanceTimersByTimeAsync(0) expect(rendered.queryAllByLabelText(/^Query key /)).toHaveLength(0) queryClient.setQueryData(['after-clear'], 'restored') await vi.advanceTimersByTimeAsync(0) viewport.scrollTo({ top: viewport.scrollTop }) expect(rendered.getByLabelText('Query key ["after-clear"]')).toBeVisible() }) it('should update the query list once when clearing the query cache', async () => { seedQueries() const rendered = renderDevtools({ initialIsOpen: true }) const styleChanges = await countStyleChanges(rendered.container, () => fireEvent.click(rendered.getByLabelText('Clear query cache')), ) expect(styleChanges).toBe(1) expect(rendered.queryAllByLabelText(/^Query key /)).toHaveLength(0) }) it('should update the query list once when the query client clears the cache', async () => { seedQueries() const rendered = renderDevtools({ initialIsOpen: true }) const styleChanges = await countStyleChanges(rendered.container, () => queryClient.clear(), ) expect(styleChanges).toBe(1) expect(rendered.queryAllByLabelText(/^Query key /)).toHaveLength(0) }) it('should update the query list once when the query client removes queries', async () => { seedQueries() const rendered = renderDevtools( { initialIsOpen: true }, { 'TanstackQueryDevtools.sort': 'query hash' }, ) const styleChanges = await countStyleChanges(rendered.container, () => queryClient.removeQueries({ predicate: (query) => String(query.queryKey[0]) < 'query-0500', }), ) expect(styleChanges).toBe(1) expect( rendered.queryByLabelText('Query key ["query-0499"]'), ).not.toBeInTheDocument() expect(rendered.getByLabelText('Query key ["query-0500"]')).toBeVisible() }) it('should read the mutation cache as often for clearing many mutations as for clearing one', async () => { const mutationCache = queryClient.getMutationCache() const buildMutations = (count: number) => { for (let index = 0; index < count; index++) { mutationCache.build(queryClient, { mutationKey: [`mutation-${index}`], }) } } const rendered = renderDevtools({ initialIsOpen: true }) fireEvent.click(rendered.getByText('Mutations')) const getAll = vi.spyOn(mutationCache, 'getAll') buildMutations(1) await vi.advanceTimersByTimeAsync(0) getAll.mockClear() mutationCache.clear() await vi.advanceTimersByTimeAsync(0) const readsForOne = getAll.mock.calls.length buildMutations(1000) await vi.advanceTimersByTimeAsync(0) getAll.mockClear() mutationCache.clear() await vi.advanceTimersByTimeAsync(0) expect(getAll).toHaveBeenCalledTimes(readsForOne) expect( rendered.queryAllByLabelText(/^Mutation submitted at /), ).toHaveLength(0) }) it('should keep query clicks aligned after a same-count sort change', () => { seedQueries() const rendered = renderDevtools( { initialIsOpen: true }, { 'TanstackQueryDevtools.sort': 'query hash' }, ) const viewport = getViewport(rendered.container, 'queries') viewport.scrollTo({ top: 14000 }) fireEvent.click(rendered.getByLabelText('Sort order ascending')) const row = rendered.getAllByLabelText(/^Query key /)[5] assert(row) const match = row.getAttribute('aria-label')?.match(/query-(\d+)/) assert(match?.[1]) fireEvent.click(row) expect( rendered.getByDisplayValue(`data-${Number(match[1])}`), ).toBeVisible() }) it('should keep mutation clicks aligned after a same-count sort change', () => { for (let index = 0; index < 100; index++) { queryClient.getMutationCache().build(queryClient, { mutationKey: [`reorder-${index}`], }) } const rendered = renderDevtools({ initialIsOpen: true }) fireEvent.click(rendered.getByText('Mutations')) const viewport = getViewport(rendered.container, 'mutations') viewport.scrollTo({ top: 1400 }) fireEvent.click(rendered.getByLabelText('Sort order ascending')) const row = rendered.getAllByLabelText(/^Mutation submitted at /)[5] assert(row) const key = row.textContent.match(/reorder-\d+/)?.[0] assert(key) fireEvent.click(row) expect( rendered.container.querySelector('.tsqd-query-details-summary'), ).toHaveTextContent(key) }) it('should bound mutation rows, preserve offscreen details, and filter from a distant offset', async () => { const mutations = Array.from({ length: 2000 }, (_, index) => queryClient.getMutationCache().build(queryClient, { mutationKey: [ index === 1999 ? 'mutation-target' : `mutation-${index}`, ], mutationFn: () => Promise.resolve(`result-${index}`), }), ) const selected = mutations[0] assert(selected) const rendered = renderDevtools({ initialIsOpen: true }) fireEvent.click(rendered.getByText('Mutations')) expect( rendered.getAllByLabelText(/^Mutation submitted at /).length, ).toBeLessThan(100) const viewport = getViewport(rendered.container, 'mutations') viewport.scrollTo({ top: viewport.scrollHeight }) const selectedRow = rendered .getByText(/\["mutation-0"\]/) .closest('button') assert(selectedRow) fireEvent.click(selectedRow) viewport.scrollTo({ top: 14000 }) expect( rendered.queryByText(/\["mutation-0"\]/, { selector: 'code' }), ).not.toBeInTheDocument() await selected.execute({}) await vi.advanceTimersByTimeAsync(0) expect(rendered.getByText('Mutation Details')).toBeVisible() expect(rendered.container).toHaveTextContent('result-0') expect( rendered.queryByText(/\["mutation-0"\]/, { selector: 'code' }), ).not.toBeInTheDocument() viewport.scrollTo({ top: viewport.scrollHeight }) fireEvent.input( rendered.getByLabelText('Filter mutations by mutation key'), { target: { value: 'mutation-target' }, }, ) viewport.scrollTo({ top: viewport.scrollTop }) expect( rendered.getAllByLabelText(/^Mutation submitted at /), ).toHaveLength(1) expect( rendered.getByText(/\["mutation-target"\]/, { selector: 'code' }), ).toBeVisible() fireEvent.click(rendered.getByLabelText('Clear query cache')) await vi.advanceTimersByTimeAsync(0) expect( rendered.queryAllByLabelText(/^Mutation submitted at /), ).toHaveLength(0) }) }) it('should keep measured panel widths independent', () => { let firstState!: ReturnType let secondState!: ReturnType const first = renderDevtools({ initialIsOpen: true }, {}, (state) => { firstState = state }) renderDevtools({ initialIsOpen: true }, {}, (state) => { secondState = state }) const panel = first.container.querySelector('aside')! for (const observer of resizeObservers) { const observed = vi .mocked(observer.observe) .mock.calls.some(([target]) => target === panel) if (observed) { ;( observer as ResizeObserver & { callback: ResizeObserverCallback } ).callback( [ { target: panel, contentRect: new DOMRectReadOnly(0, 0, 400, 500), borderBoxSize: [], contentBoxSize: [], devicePixelContentBoxSize: [], }, ], observer, ) } } expect(firstState.panelWidth()).toBe(400) expect(secondState.panelWidth()).toBe(1000) }) describe.each(['full', 'embedded'] as const)( '%s instance isolation', (mode) => { function mount(client = queryClient, manager = onlineManager) { return mode === 'full' ? renderDevtools({ client, onlineManager: manager, initialIsOpen: true, }) : render(() => ( )) } it('should keep cache notifications and cleanup independent for the same query key', async () => { const secondClient = new QueryClient() queryClient.setQueryData(['shared-key'], 'first-data') secondClient.setQueryData(['shared-key'], 'second-data') const firstRender = mount() const secondRender = mount(secondClient) const first = within(firstRender.container) const second = within(secondRender.container) fireEvent.click(first.getByLabelText('Query key ["shared-key"]')) fireEvent.click(second.getByLabelText('Query key ["shared-key"]')) secondClient.setQueryData(['shared-key'], 'updated-second') await vi.advanceTimersByTimeAsync(0) expect(first.getByDisplayValue('first-data')).toBeInTheDocument() expect( first.queryByDisplayValue('updated-second'), ).not.toBeInTheDocument() expect(second.getByDisplayValue('updated-second')).toBeInTheDocument() secondRender.unmount() queryClient.setQueryData(['shared-key'], 'updated-first') await vi.advanceTimersByTimeAsync(0) expect(first.getByDisplayValue('updated-first')).toBeInTheDocument() secondClient.clear() }) it('should keep mutation selection, notifications, and cleanup independent', async () => { const secondClient = new QueryClient() const firstMutation = queryClient .getMutationCache() .build(queryClient, { mutationKey: ['mutation-a'], mutationFn: () => Promise.resolve('first-result'), }) const secondMutation = secondClient .getMutationCache() .build(secondClient, { mutationKey: ['mutation-b'], mutationFn: () => Promise.resolve('second-result'), }) const firstRender = mount() const secondRender = mount(secondClient) const first = within(firstRender.container) const second = within(secondRender.container) fireEvent.click(first.getByText('Mutations')) fireEvent.click(second.getByText('Mutations')) await firstMutation.execute({}) await secondMutation.execute({}) await vi.advanceTimersByTimeAsync(0) fireEvent.click(first.getByLabelText(/Mutation submitted at/)) expect(second.queryByText('Mutation Details')).not.toBeInTheDocument() fireEvent.click(second.getByLabelText(/Mutation submitted at/)) expect(first.getByText('Mutation Details')).toBeInTheDocument() expect(second.getByText('Mutation Details')).toBeInTheDocument() await secondMutation.execute({}) await vi.advanceTimersByTimeAsync(0) expect(firstRender.container).toHaveTextContent('first-result') expect(firstRender.container).not.toHaveTextContent('second-result') secondRender.unmount() await firstMutation.execute({}) await vi.advanceTimersByTimeAsync(0) expect(first.getByText('Mutation Details')).toBeInTheDocument() secondClient.clear() }) it('should keep offline indicators independent for different online managers', () => { const Manager = onlineManager.constructor as new () => typeof onlineManager const firstManager = new Manager() const secondManager = new Manager() firstManager.setOnline(false) const firstRender = mount(queryClient, firstManager) const secondRender = mount(queryClient, secondManager) const first = within(firstRender.container) const second = within(secondRender.container) expect( first.getByLabelText('Unset offline mocking behavior'), ).toHaveAttribute('aria-pressed', 'true') expect(second.getByLabelText('Mock offline behavior')).toHaveAttribute( 'aria-pressed', 'false', ) firstManager.setOnline(true) expect(first.getByLabelText('Mock offline behavior')).toHaveAttribute( 'aria-pressed', 'false', ) secondRender.unmount() }) it('should reflect the supplied online manager in both instances', () => { const firstRender = mount() const secondRender = mount() const first = within(firstRender.container) const second = within(secondRender.container) fireEvent.click(first.getByLabelText('Mock offline behavior')) expect( first.getByLabelText('Unset offline mocking behavior'), ).toHaveAttribute('aria-pressed', 'true') expect( second.getByLabelText('Unset offline mocking behavior'), ).toHaveAttribute('aria-pressed', 'true') secondRender.unmount() onlineManager.setOnline(true) expect(first.getByLabelText('Mock offline behavior')).toHaveAttribute( 'aria-pressed', 'false', ) }) it('should switch cache subscriptions when the client changes', async () => { const secondClient = new QueryClient() queryClient.setQueryData(['switch-key'], 'old-client') secondClient.setQueryData(['switch-key'], 'new-client') const [client, setClient] = createSignal(queryClient) const Component = mode === 'full' ? DevtoolsComponent : DevtoolsPanelComponent const rendered = render(() => ( )) const panel = within(rendered.container) fireEvent.click(panel.getByLabelText('Query key ["switch-key"]')) expect(panel.getByDisplayValue('old-client')).toBeInTheDocument() setClient(secondClient) expect(panel.getByDisplayValue('new-client')).toBeInTheDocument() secondClient.setQueryData(['switch-key'], 'new-update') await vi.advanceTimersByTimeAsync(0) expect(panel.getByDisplayValue('new-update')).toBeInTheDocument() queryClient.setQueryData(['switch-key'], 'old-update') await vi.advanceTimersByTimeAsync(0) expect(panel.getByDisplayValue('new-update')).toBeInTheDocument() rendered.unmount() secondClient.clear() }) it('should drop pending query cache updates of the previous client when the client changes', async () => { const secondClient = new QueryClient() queryClient.setQueryData(['switch-key'], 'old-client') secondClient.setQueryData(['switch-key'], 'new-client') const [client, setClient] = createSignal(queryClient) const Component = mode === 'full' ? DevtoolsComponent : DevtoolsPanelComponent const rendered = render(() => ( )) const panel = within(rendered.container) fireEvent.click(panel.getByLabelText('Query key ["switch-key"]')) expect(panel.getByDisplayValue('old-client')).toBeInTheDocument() queryClient.setQueryData(['switch-key'], 'pending-old-update') setClient(secondClient) await vi.advanceTimersByTimeAsync(0) expect(panel.getByDisplayValue('new-client')).toBeInTheDocument() expect( panel.queryByDisplayValue('pending-old-update'), ).not.toBeInTheDocument() rendered.unmount() secondClient.clear() }) it('should switch mutation cache subscriptions when the client changes', async () => { const secondClient = new QueryClient() const [client, setClient] = createSignal(queryClient) const Component = mode === 'full' ? DevtoolsComponent : DevtoolsPanelComponent const rendered = render(() => ( )) const panel = within(rendered.container) fireEvent.click(panel.getByText('Mutations')) setClient(secondClient) await secondClient .getMutationCache() .build(secondClient, { mutationKey: ['switch-mutation'], mutationFn: () => Promise.resolve('new-result'), }) .execute({}) await vi.advanceTimersByTimeAsync(0) expect(panel.getAllByLabelText(/Mutation submitted at/)).toHaveLength(1) rendered.unmount() secondClient.clear() }) it('should drop queued mutation cache updates from the previous client', async () => { const secondClient = new QueryClient() const [client, setClient] = createSignal(queryClient) const Component = mode === 'full' ? DevtoolsComponent : DevtoolsPanelComponent const rendered = render(() => ( )) const panel = within(rendered.container) fireEvent.click(panel.getByText('Mutations')) void queryClient .getMutationCache() .build(queryClient, { mutationKey: ['previous-mutation'], mutationFn: () => new Promise(noop), }) .execute({}) setClient(secondClient) await vi.advanceTimersByTimeAsync(0) expect(panel.getByLabelText('Pending: 0')).toBeInTheDocument() rendered.unmount() secondClient.clear() }) it('should toggle the supplied online manager when the offline button is clicked', () => { const Manager = onlineManager.constructor as new () => typeof onlineManager const manager = new Manager() const panel = within(mount(queryClient, manager).container) fireEvent.click(panel.getByLabelText('Mock offline behavior')) expect(manager.isOnline()).toBe(false) expect(onlineManager.isOnline()).toBe(true) expect( panel.getByLabelText('Unset offline mocking behavior'), ).toHaveAttribute('aria-pressed', 'true') }) it('should keep query selection independent between clients', () => { const secondClient = new QueryClient() queryClient.setQueryData(['isolation-a'], 'a') secondClient.setQueryData(['isolation-b'], 'b') const first = within(mount().container) const secondRender = mount(secondClient) const second = within(secondRender.container) fireEvent.click(first.getByLabelText('Query key ["isolation-a"]')) expect(first.getByText('Query Details')).toBeInTheDocument() expect(second.queryByText('Query Details')).not.toBeInTheDocument() fireEvent.click(second.getByLabelText('Query key ["isolation-b"]')) expect(second.getByText('Query Details')).toBeInTheDocument() expect(first.getByText('Query Details')).toBeInTheDocument() secondRender.unmount() secondClient.clear() }) }, ) describe('initial state', () => { it('should render the open devtools button', () => { const rendered = renderDevtools() expect( rendered.getByLabelText('Open Tanstack query devtools'), ).toBeInTheDocument() }) it('should not render the panel by default', () => { const rendered = renderDevtools() expect( rendered.queryByLabelText('Tanstack query devtools'), ).not.toBeInTheDocument() }) it('should render the panel when "initialIsOpen" is "true"', () => { const rendered = renderDevtools({ initialIsOpen: true }) expect( rendered.getByLabelText('Tanstack query devtools'), ).toBeInTheDocument() }) it('should render the panel when "localStore.open" is "true"', () => { const rendered = renderDevtools( {}, { 'TanstackQueryDevtools.open': 'true' }, ) expect( rendered.getByLabelText('Tanstack query devtools'), ).toBeInTheDocument() }) it('should not render the panel when "localStore.open" is "false" even if "initialIsOpen" is "true"', () => { const rendered = renderDevtools( { initialIsOpen: true }, { 'TanstackQueryDevtools.open': 'false' }, ) expect( rendered.queryByLabelText('Tanstack query devtools'), ).not.toBeInTheDocument() }) }) describe('open and close', () => { it('should render the panel when the open button is clicked', () => { const rendered = renderDevtools() fireEvent.click(rendered.getByLabelText('Open Tanstack query devtools')) expect( rendered.getByLabelText('Tanstack query devtools'), ).toBeInTheDocument() }) it('should hide the open button when the panel is open', () => { const rendered = renderDevtools() fireEvent.click(rendered.getByLabelText('Open Tanstack query devtools')) expect( rendered.queryByLabelText('Open Tanstack query devtools'), ).not.toBeInTheDocument() }) it('should hide the panel when the close button is clicked', () => { const rendered = renderDevtools({ initialIsOpen: true }) fireEvent.click(rendered.getByLabelText('Close tanstack query devtools')) expect( rendered.queryByLabelText('Tanstack query devtools'), ).not.toBeInTheDocument() }) it('should render the open button after the panel is closed', () => { const rendered = renderDevtools({ initialIsOpen: true }) fireEvent.click(rendered.getByLabelText('Close tanstack query devtools')) expect( rendered.getByLabelText('Open Tanstack query devtools'), ).toBeInTheDocument() }) it('should persist "open" as "true" to "localStorage" when the open button is clicked', () => { const rendered = renderDevtools() fireEvent.click(rendered.getByLabelText('Open Tanstack query devtools')) expect(localStorage.getItem('TanstackQueryDevtools.open')).toBe('true') }) it('should persist "open" as "false" to "localStorage" when the close button is clicked', () => { const rendered = renderDevtools({ initialIsOpen: true }) fireEvent.click(rendered.getByLabelText('Close tanstack query devtools')) expect(localStorage.getItem('TanstackQueryDevtools.open')).toBe('false') }) }) describe('query list', () => { it('should render a row for each query in the cache', () => { queryClient.setQueryData(['posts'], [{ id: 1 }]) queryClient.setQueryData(['users', 'me'], { id: 'u1' }) const rendered = renderDevtools({ initialIsOpen: true }) expect( rendered.getByLabelText(/Query key \["posts"\]/), ).toBeInTheDocument() expect( rendered.getByLabelText(/Query key \["users","me"\]/), ).toBeInTheDocument() }) it('should reflect a newly added query reactively', async () => { const rendered = renderDevtools({ initialIsOpen: true }) expect( rendered.queryByLabelText(/Query key \["new"\]/), ).not.toBeInTheDocument() queryClient.setQueryData(['new'], 'hello') await vi.advanceTimersByTimeAsync(0) expect(rendered.getByLabelText(/Query key \["new"\]/)).toBeInTheDocument() }) it('should filter queries by "queryHash"', () => { queryClient.setQueryData(['posts'], []) queryClient.setQueryData(['users'], []) const rendered = renderDevtools({ initialIsOpen: true }) fireEvent.input(rendered.getByLabelText('Filter queries by query key'), { target: { value: 'posts' }, }) expect( rendered.getByLabelText(/Query key \["posts"\]/), ).toBeInTheDocument() expect( rendered.queryByLabelText(/Query key \["users"\]/), ).not.toBeInTheDocument() }) it('should cycle and persist the filter scope', () => { const rendered = renderDevtools({ initialIsOpen: true }) const scope = rendered.getByRole('button', { name: /^Filter scope: / }) expect(scope).toHaveAccessibleName('Filter scope: Key') fireEvent.click(scope) expect(scope).toHaveAccessibleName('Filter scope: Data') expect(localStorage.getItem('TanstackQueryDevtools.filterScope')).toBe( 'data', ) expect( rendered.getByLabelText('Filter queries by query data'), ).toBeInTheDocument() fireEvent.click(scope) expect(scope).toHaveAccessibleName('Filter scope: All') expect( rendered.getByLabelText('Filter queries by query key or data'), ).toBeInTheDocument() fireEvent.click(scope) expect(scope).toHaveAccessibleName('Filter scope: Key') }) it('should restore a persisted filter scope and ignore unknown values', () => { const restored = renderDevtools( { initialIsOpen: true }, { 'TanstackQueryDevtools.filterScope': 'all' }, ) expect( restored.getByRole('button', { name: 'Filter scope: All' }), ).toBeInTheDocument() cleanup() const fallback = renderDevtools( { initialIsOpen: true }, { 'TanstackQueryDevtools.filterScope': 'bogus' }, ) expect( fallback.getByRole('button', { name: 'Filter scope: Key' }), ).toBeInTheDocument() }) it('should filter queries by data keys and values in the "data" scope', () => { queryClient.setQueryData(['posts'], [{ id: 1, author: 'Alice' }]) queryClient.setQueryData(['users'], { alice: { role: 'admin' } }) queryClient.setQueryData(['alice-settings'], { theme: 'dark' }) const rendered = renderDevtools( { initialIsOpen: true }, { 'TanstackQueryDevtools.filterScope': 'data' }, ) const filter = rendered.getByLabelText('Filter queries by query data') fireEvent.input(filter, { target: { value: 'ALICE' } }) expect(rendered.getByLabelText('Query key ["posts"]')).toBeInTheDocument() expect(rendered.getByLabelText('Query key ["users"]')).toBeInTheDocument() expect( rendered.queryByLabelText('Query key ["alice-settings"]'), ).not.toBeInTheDocument() fireEvent.input(filter, { target: { value: 'admin' } }) expect(rendered.getAllByLabelText(/^Query key /)).toHaveLength(1) expect(rendered.getByLabelText('Query key ["users"]')).toBeInTheDocument() }) it('should match either the key or the data in the "all" scope', () => { queryClient.setQueryData(['posts'], { author: 'alice' }) queryClient.setQueryData(['alice-settings'], { theme: 'dark' }) queryClient.setQueryData(['users'], { name: 'bob' }) const rendered = renderDevtools( { initialIsOpen: true }, { 'TanstackQueryDevtools.filterScope': 'all' }, ) fireEvent.input( rendered.getByLabelText('Filter queries by query key or data'), { target: { value: 'alice' } }, ) expect(rendered.getByLabelText('Query key ["posts"]')).toBeInTheDocument() expect( rendered.getByLabelText('Query key ["alice-settings"]'), ).toBeInTheDocument() expect( rendered.queryByLabelText('Query key ["users"]'), ).not.toBeInTheDocument() }) it('should update data filter results when query data changes', async () => { queryClient.setQueryData(['posts'], { status: 'draft' }) queryClient.setQueryData(['users'], { status: 'active' }) const rendered = renderDevtools( { initialIsOpen: true }, { 'TanstackQueryDevtools.filterScope': 'data' }, ) fireEvent.input(rendered.getByLabelText('Filter queries by query data'), { target: { value: 'published' }, }) expect(rendered.queryAllByLabelText(/^Query key /)).toHaveLength(0) queryClient.setQueryData(['posts'], { status: 'published' }) await vi.advanceTimersByTimeAsync(0) expect(rendered.getByLabelText('Query key ["posts"]')).toBeInTheDocument() queryClient.setQueryData(['posts'], { status: 'archived' }) await vi.advanceTimersByTimeAsync(0) expect(rendered.queryAllByLabelText(/^Query key /)).toHaveLength(0) }) it('should keep the previous results until a slow data search for the latest filter is ready', async () => { for (let index = 0; index < 6; index++) { queryClient.setQueryData(['item', index], { name: index % 2 ? 'needle' : 'hay', }) } const rendered = renderDevtools( { initialIsOpen: true }, { 'TanstackQueryDevtools.filterScope': 'data' }, ) const filter = rendered.getByLabelText('Filter queries by query data') // Every call takes 5ms, so each task only builds one search text let now = 0 vi.spyOn(performance, 'now').mockImplementation(() => (now += 5)) fireEvent.input(filter, { target: { value: 'needle' } }) expect(rendered.getAllByLabelText(/^Query key /)).toHaveLength(6) fireEvent.input(filter, { target: { value: 'hay' } }) expect(rendered.getAllByLabelText(/^Query key /)).toHaveLength(6) await vi.advanceTimersByTimeAsync(50) expect( rendered .getAllByLabelText(/^Query key /) .map((row) => row.getAttribute('aria-label')), ).toStrictEqual([ 'Query key ["item",0]', 'Query key ["item",2]', 'Query key ["item",4]', ]) }) it('should clear all queries when the clear cache button is clicked', async () => { queryClient.setQueryData(['posts'], []) queryClient.setQueryData(['users'], []) const rendered = renderDevtools({ initialIsOpen: true }) fireEvent.click(rendered.getByLabelText('Clear query cache')) await vi.advanceTimersByTimeAsync(0) expect( rendered.queryByLabelText(/Query key \["posts"\]/), ).not.toBeInTheDocument() expect( rendered.queryByLabelText(/Query key \["users"\]/), ).not.toBeInTheDocument() }) it('should dispatch a "CLEAR_MUTATION_CACHE" event when clear cache is clicked in mutations view', () => { const rendered = renderDevtools({ initialIsOpen: true }) fireEvent.click(rendered.getByText('Mutations')) const listener = vi.fn() window.addEventListener('@tanstack/query-devtools-event', listener) try { fireEvent.click(rendered.getByLabelText('Clear query cache')) const dispatched = listener.mock.calls.some( ([e]) => (e as CustomEvent).detail.type === 'CLEAR_MUTATION_CACHE', ) expect(dispatched).toBe(true) } finally { window.removeEventListener('@tanstack/query-devtools-event', listener) } }) it('should render a query row when a hydrated query uses a custom hash function', async () => { queryClient.query({ queryKey: ['posts'], queryFn: () => [{ id: 1 }], queryKeyHashFn: () => 'custom-posts-hash', }) await vi.advanceTimersByTimeAsync(0) const dehydratedState = dehydrate(queryClient) queryClient = new QueryClient() hydrate(queryClient, dehydratedState) const rendered = renderDevtools({ initialIsOpen: true }) expect( rendered.getByLabelText(/Query key custom-posts-hash/), ).toBeInTheDocument() }) }) describe('view toggle', () => { it('should switch to mutations view when the mutations toggle is clicked', () => { const rendered = renderDevtools({ initialIsOpen: true }) fireEvent.click(rendered.getByText('Mutations')) expect( rendered.container.querySelector('.tsqd-mutations-container'), ).not.toBeNull() }) it('should render mutations in the mutations view', async () => { const rendered = renderDevtools({ initialIsOpen: true }) fireEvent.click(rendered.getByText('Mutations')) const mutation = queryClient.getMutationCache().build(queryClient, { mutationKey: ['add-post'], mutationFn: () => Promise.resolve('ok'), }) mutation.execute({}) await vi.advanceTimersByTimeAsync(0) expect( rendered.getByLabelText(/Mutation submitted at/), ).toBeInTheDocument() }) it('should render an idle mutation that has been built but not executed', async () => { const rendered = renderDevtools({ initialIsOpen: true }) fireEvent.click(rendered.getByText('Mutations')) queryClient.getMutationCache().build(queryClient, { mutationKey: ['idle-mut'], mutationFn: () => Promise.resolve('ok'), }) await vi.advanceTimersByTimeAsync(0) expect( rendered.getByLabelText(/Mutation submitted at/), ).toBeInTheDocument() }) }) describe('disabled and static queries', () => { it('should mark a disabled query in the row label', () => { const observer = queryClient.getQueryCache().build(queryClient, { queryKey: ['disabled-q'], queryFn: () => 'x', }) observer.setOptions({ ...observer.options, enabled: false, } as typeof observer.options) observer.setState({ ...observer.state, data: 'x' }) const rendered = renderDevtools({ initialIsOpen: true }) expect(rendered.getByLabelText(/disabled/)).toBeInTheDocument() }) it('should render a "static" indicator for a query with "staleTime: \'static\'"', () => { const query = queryClient.getQueryCache().build(queryClient, { queryKey: ['static-q'], queryFn: () => 'x', }) const observer = new QueryObserver(queryClient, { queryKey: ['static-q'], queryFn: () => 'x', staleTime: 'static', }) query.addObserver(observer) query.setState({ ...query.state, data: 'x' }) const rendered = renderDevtools({ initialIsOpen: true }) expect(rendered.getByText('static')).toBeInTheDocument() expect(rendered.getByLabelText(/, static/)).toBeInTheDocument() }) it('should render a query row when an object query key is mutated in place', () => { const filters = { page: 1 } queryClient.setQueryData(['mutable-key', filters], 'x') filters.page = 2 const rendered = renderDevtools({ initialIsOpen: true }) expect( rendered.getByLabelText(/Query key \["mutable-key",\{"page":1\}\]/), ).toBeInTheDocument() }) }) describe('picture-in-picture', () => { type FakePipWindow = Pick< Window, | 'document' | 'innerWidth' | 'innerHeight' | 'addEventListener' | 'removeEventListener' | 'close' > function stubPipWindow( overrides: Partial< Pick > = {}, ) { const pipDocument = document.implementation.createHTMLDocument('PiP') Object.defineProperty(pipDocument, 'defaultView', { value: window }) const listeners = new Map() const fakeWindow: FakePipWindow = { document: pipDocument, innerWidth: 800, innerHeight: 600, addEventListener: vi.fn< (event: string, handler: EventListener) => void >((event: string, handler: EventListener) => { listeners.set(event, handler) }), removeEventListener: vi.fn<(event: string) => void>((event: string) => { listeners.delete(event) }), close: vi.fn<() => void>(), ...overrides, } const open = vi.fn< () => Pick< Window, | 'close' | 'addEventListener' | 'removeEventListener' | 'document' | 'innerWidth' | 'innerHeight' > >(() => fakeWindow) vi.stubGlobal('open', open) return { pipDocument, fakeWindow, open, fire: (event: string) => { listeners.get(event)?.(new Event(event)) }, } } it('should open a PiP window when the picture-in-picture button is clicked', () => { const { open } = stubPipWindow() const rendered = renderDevtools({ initialIsOpen: true }) fireEvent.click( rendered.getByLabelText('Open in picture-in-picture mode'), ) expect(open).toHaveBeenCalledWith( '', 'TSQD-Devtools-Panel', expect.stringMatching(/^width=\d+,height=\d+,popup$/), ) expect(localStorage.getItem('TanstackQueryDevtools.pip_open')).toBe( 'true', ) }) it('should hide the in-page panel while a PiP window is open', () => { stubPipWindow() const rendered = renderDevtools({ initialIsOpen: true }) fireEvent.click( rendered.getByLabelText('Open in picture-in-picture mode'), ) expect( rendered.container.querySelector('.tsqd-main-panel-container'), ).toBeNull() }) it('should restore the in-page panel when the PiP window is closed', () => { const { fire } = stubPipWindow() const rendered = renderDevtools({ initialIsOpen: true }) fireEvent.click( rendered.getByLabelText('Open in picture-in-picture mode'), ) fire('pagehide') expect( rendered.getByLabelText('Open in picture-in-picture mode'), ).toBeInTheDocument() }) it('should render the PiP panel with the narrow layout when the PiP window is below the second breakpoint', () => { // secondBreakpoint = 796; pick a width comfortably below it so the // PiP panel evaluates its narrow (`flex-direction: column`) branch. const { pipDocument } = stubPipWindow({ innerWidth: 500 }) queryClient.setQueryData(['narrow-pip-query'], { hello: 'world' }) const rendered = renderDevtools({ initialIsOpen: true }) fireEvent.click( rendered.getByLabelText('Open in picture-in-picture mode'), ) expect( pipDocument.querySelector( '[aria-label="Close Tanstack query devtools"]', ), ).not.toBeNull() expect( pipDocument.querySelector('[aria-label*="narrow-pip-query"]'), ).not.toBeNull() }) it('should render the PiP panel with "dir" set to "ltr"', () => { const { pipDocument } = stubPipWindow() const rendered = renderDevtools({ initialIsOpen: true }) fireEvent.click( rendered.getByLabelText('Open in picture-in-picture mode'), ) expect(pipDocument.querySelector('.tsqd-main-panel')).toHaveAttribute( 'dir', 'ltr', ) }) }) describe('status counts', () => { it('should render status count badges', () => { const rendered = renderDevtools({ initialIsOpen: true }) expect(rendered.getByLabelText(/Fresh: \d+/)).toBeInTheDocument() expect(rendered.getByLabelText(/Stale: \d+/)).toBeInTheDocument() expect(rendered.getByLabelText(/Fetching: \d+/)).toBeInTheDocument() expect(rendered.getByLabelText(/Paused: \d+/)).toBeInTheDocument() expect(rendered.getByLabelText(/Inactive: \d+/)).toBeInTheDocument() }) it('should reflect the inactive count when a query is added without observers', async () => { const rendered = renderDevtools({ initialIsOpen: true }) expect(rendered.getByLabelText('Inactive: 0')).toBeInTheDocument() queryClient.setQueryData(['posts'], [{ id: 1 }]) await vi.advanceTimersByTimeAsync(0) expect(rendered.getByLabelText('Inactive: 1')).toBeInTheDocument() }) }) describe('status tooltip', () => { it('should show the tooltip on mouse enter and hide it on mouse leave when the panel is narrow', () => { // Re-stub ResizeObserver with a narrow width (< secondBreakpoint = 796) // so `showLabel()` is false and the tooltip is rendered conditionally on // hover/focus. vi.stubGlobal( 'ResizeObserver', class { callback: ResizeObserverCallback constructor(callback: ResizeObserverCallback) { this.callback = callback } observe = vi.fn<(target: Element) => void>((target: Element) => { this.callback( [ { target, contentRect: { width: 500, height: 500 } as DOMRectReadOnly, } as ResizeObserverEntry, ], this, ) }) unobserve = vi.fn() disconnect = vi.fn() }, ) const rendered = renderDevtools({ initialIsOpen: true }) const fresh = rendered.getByLabelText('Fresh: 0') expect(rendered.queryByRole('tooltip')).not.toBeInTheDocument() fireEvent.mouseEnter(fresh) expect(rendered.getByRole('tooltip')).toBeInTheDocument() fireEvent.mouseLeave(fresh) expect(rendered.queryByRole('tooltip')).not.toBeInTheDocument() }) it('should show the tooltip on focus and hide it on blur when the panel is narrow', () => { vi.stubGlobal( 'ResizeObserver', class { callback: ResizeObserverCallback constructor(callback: ResizeObserverCallback) { this.callback = callback } observe = vi.fn<(target: Element) => void>((target: Element) => { this.callback( [ { target, contentRect: { width: 500, height: 500 } as DOMRectReadOnly, } as ResizeObserverEntry, ], this, ) }) unobserve = vi.fn() disconnect = vi.fn() }, ) const rendered = renderDevtools({ initialIsOpen: true }) const fresh = rendered.getByLabelText('Fresh: 0') expect(rendered.queryByRole('tooltip')).not.toBeInTheDocument() fireEvent.focus(fresh) expect(rendered.getByRole('tooltip')).toBeInTheDocument() fireEvent.blur(fresh) expect(rendered.queryByRole('tooltip')).not.toBeInTheDocument() }) }) describe('Data Explorer search', () => { it('should search only query Data and reset search when the selection changes', async () => { queryClient.setQueryData(['search-first'], { nested: { name: 'first needle' }, }) queryClient.setQueryData(['search-second'], { nested: { name: 'second' }, }) const rendered = renderDevtools({ initialIsOpen: true }) fireEvent.click(rendered.getByLabelText('Query key ["search-first"]')) expect(rendered.getAllByLabelText('Search data')).toHaveLength(1) const search = rendered.getByRole('searchbox', { name: 'Search data' }) fireEvent.input(search, { target: { value: 'NEEDLE' } }) vi.advanceTimersByTime(150) const dataContainer = rendered.container.querySelector( '.tsqd-query-details-data-explorer', ) assert(dataContainer instanceof HTMLElement) const data = within(dataContainer) expect(data.getByLabelText('name:')).toHaveValue('first needle') expect(data.getByLabelText('name:')).toHaveAttribute( 'data-search-match', 'true', ) queryClient.setQueryData(['search-first'], { nested: { name: 'updated needle' }, }) await vi.advanceTimersByTimeAsync(0) expect(data.getByLabelText('name:')).toHaveValue('updated needle') fireEvent.click(rendered.getByLabelText('Query key ["search-second"]')) expect(rendered.getByLabelText('Search data')).toHaveValue('') expect(dataContainer.querySelector('[data-search-match]')).toBeNull() }) it('should search read-only mutation Data and reset search when the selection changes', async () => { const first = queryClient.getMutationCache().build(queryClient, { mutationKey: ['search-first'], mutationFn: () => Promise.resolve({ nested: { name: 'mutation needle' } }), }) const second = queryClient.getMutationCache().build(queryClient, { mutationKey: ['search-second'], mutationFn: () => Promise.resolve({ nested: { name: 'other' } }), }) await first.execute(undefined) await second.execute(undefined) const rendered = renderDevtools({ initialIsOpen: true }) fireEvent.click(rendered.getByText('Mutations')) const rows = rendered.getAllByLabelText(/^Mutation submitted at /) const firstRow = rows.find((row) => row.textContent.includes('search-first'), ) const secondRow = rows.find((row) => row.textContent.includes('search-second'), ) assert(firstRow && secondRow) fireEvent.click(firstRow) expect(rendered.getAllByLabelText('Search data')).toHaveLength(1) fireEvent.input(rendered.getByLabelText('Search data'), { target: { value: 'needle' }, }) vi.advanceTimersByTime(150) const dataContainer = rendered.getByRole('heading', { name: 'Data Explorer', }).nextElementSibling assert(dataContainer instanceof HTMLElement) const data = within(dataContainer) expect( [...CSS.highlights.values()].flatMap((highlight) => [...highlight].map((range) => range.toString()), ), ).toContain('needle') expect(data.queryByRole('textbox')).not.toBeInTheDocument() fireEvent.click(secondRow) expect(rendered.getByLabelText('Search data')).toHaveValue('') expect( [...CSS.highlights.values()].every((highlight) => highlight.size === 0), ).toBe(true) }) it.each(['key', 'data', 'all'] as const)( 'should initialize the query Data search from the %s scope', (scope) => { queryClient.setQueryData(['needle-first'], { name: 'first needle' }) queryClient.setQueryData(['needle-second'], { name: 'second needle' }) const rendered = renderDevtools( { initialIsOpen: true }, { 'TanstackQueryDevtools.filterScope': scope }, ) fireEvent.input(rendered.getByLabelText(/^Filter queries by/), { target: { value: 'Needle' }, }) fireEvent.click(rendered.getByLabelText('Query key ["needle-first"]')) const search = rendered.getByLabelText('Search data') const initial = scope === 'key' ? '' : 'Needle' expect(search).toHaveValue(initial) expect( rendered.container.querySelectorAll('[data-search-match="true"]'), ).toHaveLength(scope === 'key' ? 0 : 1) fireEvent.input(search, { target: { value: 'first' } }) fireEvent.click(rendered.getByLabelText('Query key ["needle-second"]')) expect(search).toHaveValue(initial) }, ) it.each(['key', 'data', 'all'] as const)( 'should initialize matching mutation explorers from the %s scope', async (scope) => { for (const source of ['data', 'variables', 'both']) { await queryClient .getMutationCache() .build(queryClient, { mutationKey: ['needle', source], mutationFn: () => Promise.resolve({ nested: { name: source === 'variables' ? 'other' : 'data needle', }, }), }) .execute({ nested: { name: source === 'data' ? 'other' : 'variable needle' }, }) } const rendered = renderDevtools( { initialIsOpen: true }, { 'TanstackQueryDevtools.filterScope': scope }, ) fireEvent.click(rendered.getByText('Mutations')) fireEvent.input(rendered.getByLabelText(/^Filter mutations by/), { target: { value: 'Needle' }, }) const rows = rendered.getAllByLabelText(/^Mutation submitted at /) for (const source of ['data', 'variables', 'both']) { const row = rows.find((item) => item.textContent.includes(source)) assert(row) fireEvent.click(row) expect(rendered.getByLabelText('Search data')).toHaveValue( scope !== 'key' && source !== 'variables' ? 'Needle' : '', ) expect(rendered.getByLabelText('Search variables')).toHaveValue( scope !== 'key' && source !== 'data' ? 'Needle' : '', ) expect(rendered.queryByText('No matches')).not.toBeInTheDocument() expect( [...CSS.highlights.values()].some((highlight) => [...highlight].some((range) => range.toString() === 'needle'), ), ).toBe(scope !== 'key') fireEvent.input(rendered.getByLabelText('Search variables'), { target: { value: 'manual' }, }) } }, ) }) describe('query details', () => { it('should open the query details panel when a query row is clicked', () => { queryClient.setQueryData(['posts'], [{ id: 1 }]) const rendered = renderDevtools({ initialIsOpen: true }) fireEvent.click(rendered.getByLabelText(/Query key \["posts"\]/)) expect(rendered.getByText('Query Details')).toBeInTheDocument() }) it('should close the query details panel when the same row is clicked again', () => { queryClient.setQueryData(['details-toggle'], [{ id: 1 }]) const rendered = renderDevtools({ initialIsOpen: true }) fireEvent.click(rendered.getByLabelText(/Query key \["details-toggle"\]/)) fireEvent.click(rendered.getByLabelText(/Query key \["details-toggle"\]/)) expect(rendered.queryByText('Query Details')).not.toBeInTheDocument() }) }) describe('query actions', () => { it('should remove the query when the "Remove" button is clicked', async () => { queryClient.setQueryData(['action-remove'], [{ id: 1 }]) const rendered = renderDevtools({ initialIsOpen: true }) fireEvent.click(rendered.getByLabelText(/Query key \["action-remove"\]/)) fireEvent.click(rendered.getByText('Remove')) await vi.advanceTimersByTimeAsync(0) expect( rendered.queryByLabelText(/Query key \["action-remove"\]/), ).not.toBeInTheDocument() }) it('should reset the query when the "Reset" button is clicked', () => { queryClient.setQueryData(['action-reset'], [{ id: 1 }]) const rendered = renderDevtools({ initialIsOpen: true }) fireEvent.click(rendered.getByLabelText(/Query key \["action-reset"\]/)) fireEvent.click(rendered.getByText('Reset')) expect(queryClient.getQueryData(['action-reset'])).toBeUndefined() }) it('should invalidate the query when the "Invalidate" button is clicked', () => { queryClient.setQueryData(['action-invalidate'], [{ id: 1 }]) const rendered = renderDevtools({ initialIsOpen: true }) fireEvent.click( rendered.getByLabelText(/Query key \["action-invalidate"\]/), ) fireEvent.click(rendered.getByText('Invalidate')) expect( queryClient.getQueryState(['action-invalidate'])?.isInvalidated, ).toBe(true) }) it('should dispatch a "REFETCH" event when "Refetch" is clicked', () => { queryClient.setQueryData(['action-refetch'], [{ id: 1 }]) const rendered = renderDevtools({ initialIsOpen: true }) const listener = vi.fn() window.addEventListener('@tanstack/query-devtools-event', listener) try { fireEvent.click( rendered.getByLabelText(/Query key \["action-refetch"\]/), ) fireEvent.click(rendered.getByText('Refetch')) const dispatched = listener.mock.calls.some( ([e]) => (e as CustomEvent).detail.type === 'REFETCH', ) expect(dispatched).toBe(true) } finally { window.removeEventListener('@tanstack/query-devtools-event', listener) } }) it('should set the query status to "error" when "Trigger Error" is clicked', () => { queryClient.setQueryData(['action-error'], [{ id: 1 }]) const rendered = renderDevtools({ initialIsOpen: true }) fireEvent.click(rendered.getByLabelText(/Query key \["action-error"\]/)) fireEvent.click(rendered.getByText('Trigger Error')) expect(queryClient.getQueryState(['action-error'])?.status).toBe('error') }) it('should restore the query status when "Restore Error" is clicked after "Trigger Error"', async () => { queryClient.setQueryData(['action-restore-error'], [{ id: 1 }]) const rendered = renderDevtools({ initialIsOpen: true }) fireEvent.click( rendered.getByLabelText(/Query key \["action-restore-error"\]/), ) fireEvent.click(rendered.getByText('Trigger Error')) await vi.advanceTimersByTimeAsync(0) fireEvent.click(rendered.getByText('Restore Error')) expect(queryClient.getQueryState(['action-restore-error'])?.status).toBe( 'pending', ) }) it('should restore the previous query options when "Restore Loading" is clicked after "Trigger Loading"', async () => { const queryFn = vi.fn<() => Promise>(() => Promise.resolve('original'), ) void queryClient .query({ queryKey: ['action-restore-loading'], queryFn, }) .catch(noop) await vi.advanceTimersByTimeAsync(0) expect(queryFn).toHaveBeenCalledTimes(1) const rendered = renderDevtools({ initialIsOpen: true }) fireEvent.click( rendered.getByLabelText(/Query key \["action-restore-loading"\]/), ) // First click puts the query into a pending state with `data: undefined` // and stashes the original options in `fetchMeta.__previousQueryOptions`. fireEvent.click(rendered.getByText('Trigger Loading')) await vi.advanceTimersByTimeAsync(0) expect( queryClient.getQueryState(['action-restore-loading'])?.status, ).toBe('pending') // Second click runs `restoreQueryAfterLoadingOrError`, which cancels the // never-resolving fetch and refetches with the stashed options. fireEvent.click(rendered.getByText('Restore Loading')) await vi.advanceTimersByTimeAsync(0) expect(queryFn).toHaveBeenCalledTimes(2) expect(queryClient.getQueryData(['action-restore-loading'])).toBe( 'original', ) }) it('should keep "Restore Loading" disabled until the restored fetch finishes', async () => { queryClient.setQueryDefaults(['action-restore-loading-disabled'], { queryFn: () => new Promise((resolve) => setTimeout(() => resolve('restored'), 10), ), }) queryClient.setQueryData(['action-restore-loading-disabled'], 'initial') const rendered = renderDevtools({ initialIsOpen: true }) fireEvent.click( rendered.getByLabelText( /Query key \["action-restore-loading-disabled"\]/, ), ) fireEvent.click(rendered.getByText('Trigger Loading')) await vi.advanceTimersByTimeAsync(0) fireEvent.click(rendered.getByText('Restore Loading')) await vi.advanceTimersByTimeAsync(0) expect(rendered.getByText('Restore Loading')).toBeDisabled() await vi.advanceTimersByTimeAsync(10) expect(rendered.getByText('Trigger Loading')).toBeEnabled() expect( queryClient.getQueryData(['action-restore-loading-disabled']), ).toBe('restored') }) }) describe('mutation details', () => { it('should open the mutation details panel when a mutation row is clicked', async () => { const rendered = renderDevtools({ initialIsOpen: true }) fireEvent.click(rendered.getByText('Mutations')) const mutation = queryClient.getMutationCache().build(queryClient, { mutationKey: ['mutation-detail'], mutationFn: () => Promise.resolve('ok'), }) mutation.execute({}) await vi.advanceTimersByTimeAsync(0) fireEvent.click(rendered.getByLabelText(/Mutation submitted at/)) expect(rendered.getByText('Mutation Details')).toBeInTheDocument() }) }) describe('mutation sort order', () => { it('should toggle the mutation sort order in the mutations view', () => { const rendered = renderDevtools({ initialIsOpen: true }) fireEvent.click(rendered.getByText('Mutations')) fireEvent.click(rendered.getByLabelText(/Sort order/)) const afterFirstToggle = localStorage.getItem( 'TanstackQueryDevtools.mutationSortOrder', ) expect(afterFirstToggle).not.toBeNull() fireEvent.click(rendered.getByLabelText(/Sort order/)) const afterSecondToggle = localStorage.getItem( 'TanstackQueryDevtools.mutationSortOrder', ) expect(afterSecondToggle).not.toBe(afterFirstToggle) }) }) describe('mutation filter', () => { it.each(['key', 'data', 'all'] as const)( 'should refresh cached mutation variables after updates in the %s scope', async (scope) => { let resolve!: () => void const variables = { name: 'before' } const mutation = queryClient.getMutationCache().build(queryClient, { mutationKey: ['update-variables'], mutationFn: async (input: typeof variables) => { await new Promise((done) => { resolve = done }) input.name = 'after' return 'ok' }, }) const pending = mutation.execute(variables) await vi.advanceTimersByTimeAsync(0) const rendered = renderDevtools( { initialIsOpen: true }, { 'TanstackQueryDevtools.filterScope': 'data' }, ) fireEvent.click(rendered.getByText('Mutations')) const filter = rendered.getByLabelText(/^Filter mutations by/) fireEvent.input(filter, { target: { value: 'before' } }) expect( rendered.getAllByLabelText(/^Mutation submitted at /), ).toHaveLength(1) // Even changes while filtering by key or with an empty term must invalidate cached text. const steps = { key: 2, data: 0, all: 1 }[scope] for (let index = 0; index < steps; index++) { fireEvent.click( rendered.getByRole('button', { name: /^Filter scope:/ }), ) } fireEvent.input(filter, { target: { value: scope === 'key' ? '' : 'before' }, }) resolve() await pending await vi.advanceTimersByTimeAsync(0) for (let index = 0; index < (3 - steps) % 3; index++) { fireEvent.click( rendered.getByRole('button', { name: /^Filter scope:/ }), ) } fireEvent.input(filter, { target: { value: 'after' } }) expect( rendered.getAllByLabelText(/^Mutation submitted at /), ).toHaveLength(1) fireEvent.input(filter, { target: { value: 'before' } }) expect( rendered.queryAllByLabelText(/^Mutation submitted at /), ).toHaveLength(0) }, ) it('should filter mutations by their "mutationKey"', async () => { const rendered = renderDevtools({ initialIsOpen: true }) fireEvent.click(rendered.getByText('Mutations')) const matching = queryClient.getMutationCache().build(queryClient, { mutationKey: ['filter-match'], mutationFn: () => Promise.resolve('ok'), }) const other = queryClient.getMutationCache().build(queryClient, { mutationKey: ['filter-other'], mutationFn: () => Promise.resolve('ok'), }) matching.execute({}) other.execute({}) await vi.advanceTimersByTimeAsync(0) expect(rendered.getAllByLabelText(/Mutation submitted at/)).toHaveLength( 2, ) fireEvent.input( rendered.getByLabelText('Filter mutations by mutation key'), { target: { value: 'filter-match' } }, ) expect(rendered.getAllByLabelText(/Mutation submitted at/)).toHaveLength( 1, ) }) it('should filter mutations by their variables or data with the shared filter scope', async () => { const rendered = renderDevtools( { initialIsOpen: true }, { 'TanstackQueryDevtools.filterScope': 'data' }, ) fireEvent.click(rendered.getByText('Mutations')) const execute = (key: string, variables: unknown, data: unknown) => queryClient .getMutationCache() .build(queryClient, { mutationKey: [key], mutationFn: () => Promise.resolve(data), }) .execute(variables) execute('by-variables', { title: 'Needle' }, 'ok') execute('by-data', { title: 'other' }, { id: 'needle-1' }) execute('needle-key', { title: 'other' }, 'ok') await vi.advanceTimersByTimeAsync(0) fireEvent.input( rendered.getByLabelText('Filter mutations by variables or data'), { target: { value: 'needle' } }, ) const keys = () => rendered .getAllByLabelText(/Mutation submitted at/) .map((row) => row.textContent) expect(keys()).toHaveLength(2) expect(keys().join()).toContain('by-variables') expect(keys().join()).toContain('by-data') fireEvent.click( rendered.getByRole('button', { name: 'Filter scope: Data' }), ) expect(keys()).toHaveLength(3) fireEvent.click( rendered.getByRole('button', { name: 'Filter scope: All' }), ) expect(keys()).toHaveLength(1) expect(keys().join()).toContain('needle-key') expect(localStorage.getItem('TanstackQueryDevtools.filterScope')).toBe( 'key', ) }) }) describe('data edit', () => { it('should switch to data editor when "Bulk Edit Data" is clicked', () => { queryClient.setQueryData(['edit-data'], { name: 'a' }) const rendered = renderDevtools({ initialIsOpen: true }) fireEvent.click(rendered.getByLabelText(/Query key \["edit-data"\]/)) fireEvent.click(rendered.getByLabelText('Bulk Edit Data')) expect( rendered.getByLabelText('Edit query data as JSON'), ).toBeInTheDocument() }) it('should save the edited data when the form is submitted', () => { queryClient.setQueryData(['edit-save'], { name: 'a' }) const rendered = renderDevtools({ initialIsOpen: true }) fireEvent.click(rendered.getByLabelText(/Query key \["edit-save"\]/)) fireEvent.click(rendered.getByLabelText('Bulk Edit Data')) const textarea = rendered.getByLabelText('Edit query data as JSON') fireEvent.input(textarea, { target: { value: JSON.stringify({ name: 'b' }) }, }) fireEvent.submit(textarea.closest('form')!) expect(queryClient.getQueryData(['edit-save'])).toStrictEqual({ name: 'b', }) }) it('should set an error state when the edited data is invalid JSON', () => { queryClient.setQueryData(['edit-invalid'], { name: 'a' }) const rendered = renderDevtools({ initialIsOpen: true }) fireEvent.click(rendered.getByLabelText(/Query key \["edit-invalid"\]/)) fireEvent.click(rendered.getByLabelText('Bulk Edit Data')) const textarea = rendered.getByLabelText('Edit query data as JSON') fireEvent.input(textarea, { target: { value: 'not json' } }) fireEvent.submit(textarea.closest('form')!) expect(rendered.getByText('Invalid Value')).toBeInTheDocument() }) it('should clear the error state when the textarea is focused after a submit failure', () => { queryClient.setQueryData(['edit-refocus'], { name: 'a' }) const rendered = renderDevtools({ initialIsOpen: true }) fireEvent.click(rendered.getByLabelText(/Query key \["edit-refocus"\]/)) fireEvent.click(rendered.getByLabelText('Bulk Edit Data')) const textarea = rendered.getByLabelText('Edit query data as JSON') fireEvent.input(textarea, { target: { value: 'not json' } }) fireEvent.submit(textarea.closest('form')!) expect(rendered.getByText('Invalid Value')).toBeInTheDocument() fireEvent.focus(textarea) expect(rendered.queryByText('Invalid Value')).not.toBeInTheDocument() }) it('should return to the data view when the editor "Cancel" button is clicked', () => { queryClient.setQueryData(['edit-cancel'], { name: 'a' }) const rendered = renderDevtools({ initialIsOpen: true }) fireEvent.click(rendered.getByLabelText(/Query key \["edit-cancel"\]/)) fireEvent.click(rendered.getByLabelText('Bulk Edit Data')) expect( rendered.getByLabelText('Edit query data as JSON'), ).toBeInTheDocument() fireEvent.click(rendered.getByText('Cancel')) expect( rendered.queryByLabelText('Edit query data as JSON'), ).not.toBeInTheDocument() expect(rendered.getByLabelText('Bulk Edit Data')).toBeInTheDocument() }) }) describe('error type select', () => { it('should render the error type select when "errorTypes" is provided', () => { queryClient.setQueryData(['error-select'], [{ id: 1 }]) const rendered = renderDevtools({ initialIsOpen: true, errorTypes: [ { name: 'NetworkError', initializer: () => new Error('Network'), }, ], }) fireEvent.click(rendered.getByLabelText(/Query key \["error-select"\]/)) expect( rendered.getByLabelText('Select error type to trigger'), ).toBeInTheDocument() }) it('should trigger error when an error type is selected', () => { queryClient.setQueryData(['error-select-trigger'], [{ id: 1 }]) const rendered = renderDevtools({ initialIsOpen: true, errorTypes: [ { name: 'NetworkError', initializer: () => new Error('Network'), }, ], }) fireEvent.click( rendered.getByLabelText(/Query key \["error-select-trigger"\]/), ) const select = rendered.getByLabelText('Select error type to trigger') fireEvent.change(select, { target: { value: 'NetworkError' } }) expect(queryClient.getQueryState(['error-select-trigger'])?.status).toBe( 'error', ) }) }) describe('sort by', () => { it('should change sort key when the sort dropdown is changed in queries view', () => { const rendered = renderDevtools({ initialIsOpen: true }) fireEvent.change(rendered.getByLabelText('Sort queries by'), { target: { value: 'last updated' }, }) expect(localStorage.getItem('TanstackQueryDevtools.sort')).toBe( 'last updated', ) }) it('should change sort key when the sort dropdown is changed in mutations view', () => { const rendered = renderDevtools({ initialIsOpen: true }) fireEvent.click(rendered.getByText('Mutations')) fireEvent.change(rendered.getByLabelText('Sort mutations by'), { target: { value: 'last updated' }, }) expect(localStorage.getItem('TanstackQueryDevtools.mutationSort')).toBe( 'last updated', ) }) it('should hide disabled queries when "hideDisabledQueries" is enabled in localStorage', () => { const disabled = new QueryObserver(queryClient, { queryKey: ['hide-test-disabled'], queryFn: () => 'x', enabled: false, }) const unsubscribe = disabled.subscribe(() => {}) queryClient.setQueryData(['hide-test-disabled'], 'x') queryClient.setQueryData(['hide-test-active'], 'y') try { const rendered = renderDevtools( { initialIsOpen: true }, { 'TanstackQueryDevtools.hideDisabledQueries': 'true' }, ) expect( rendered.queryByLabelText(/Query key \["hide-test-disabled"\]/), ).not.toBeInTheDocument() expect( rendered.getByLabelText(/Query key \["hide-test-active"\]/), ).toBeInTheDocument() } finally { unsubscribe() } }) it('should hide disabled queries when the "hideDisabledQueries" prop is true', () => { const disabled = new QueryObserver(queryClient, { queryKey: ['hide-prop-disabled'], queryFn: () => 'x', enabled: false, }) const unsubscribe = disabled.subscribe(() => {}) queryClient.setQueryData(['hide-prop-disabled'], 'x') queryClient.setQueryData(['hide-prop-active'], 'y') try { const rendered = renderDevtools({ initialIsOpen: true, hideDisabledQueries: true, }) expect( rendered.queryByLabelText(/Query key \["hide-prop-disabled"\]/), ).not.toBeInTheDocument() expect( rendered.getByLabelText(/Query key \["hide-prop-active"\]/), ).toBeInTheDocument() } finally { unsubscribe() } }) it('should prefer the "hideDisabledQueries" setting in localStorage over the prop', () => { const disabled = new QueryObserver(queryClient, { queryKey: ['hide-override-disabled'], queryFn: () => 'x', enabled: false, }) const unsubscribe = disabled.subscribe(() => {}) queryClient.setQueryData(['hide-override-disabled'], 'x') try { const rendered = renderDevtools( { initialIsOpen: true, hideDisabledQueries: true }, { 'TanstackQueryDevtools.hideDisabledQueries': 'false' }, ) expect( rendered.getByLabelText(/Query key \["hide-override-disabled"\]/), ).toBeInTheDocument() } finally { unsubscribe() } }) }) describe('sort order', () => { it('should toggle the sort order when the sort order button is clicked', () => { const rendered = renderDevtools({ initialIsOpen: true }) fireEvent.click(rendered.getByLabelText(/Sort order/)) const afterFirstToggle = localStorage.getItem( 'TanstackQueryDevtools.sortOrder', ) expect(['1', '-1']).toContain(afterFirstToggle) fireEvent.click(rendered.getByLabelText(/Sort order/)) const afterSecondToggle = localStorage.getItem( 'TanstackQueryDevtools.sortOrder', ) expect(afterSecondToggle).toBe(afterFirstToggle === '1' ? '-1' : '1') }) }) describe('settings menu', () => { it('should show "Position" sub-trigger when the settings menu is opened', () => { const rendered = renderDevtools({ initialIsOpen: true }) fireEvent.keyDown(rendered.getByLabelText('Open settings menu'), { key: 'Enter', }) // The menu is rendered through a Portal mounted on `document.body`, // outside `rendered.container`, so look it up via `document` directly. expect( document.querySelector('.tsqd-settings-menu-sub-trigger-position'), ).not.toBeNull() }) it('should open "Position" sub-menu when the sub-trigger is activated', () => { const rendered = renderDevtools({ initialIsOpen: true }) fireEvent.keyDown(rendered.getByLabelText('Open settings menu'), { key: 'Enter', }) const subTrigger = document.querySelector( '.tsqd-settings-menu-sub-trigger-position', ) expect(subTrigger).not.toBeNull() fireEvent.keyDown(subTrigger!, { key: 'ArrowRight' }) expect( document.querySelector('[aria-label="Position settings"]'), ).not.toBeNull() }) it('should persist "position" when a position radio item is selected', () => { const rendered = renderDevtools({ initialIsOpen: true }) fireEvent.keyDown(rendered.getByLabelText('Open settings menu'), { key: 'Enter', }) const subTrigger = document.querySelector( '.tsqd-settings-menu-sub-trigger-position', ) expect(subTrigger).not.toBeNull() fireEvent.keyDown(subTrigger!, { key: 'ArrowRight' }) const topItem = document.querySelector( '.tsqd-settings-menu-position-btn-top', ) expect(topItem).not.toBeNull() fireEvent.keyDown(topItem!, { key: 'Enter' }) expect(localStorage.getItem('TanstackQueryDevtools.position')).toBe('top') }) it('should open "Theme" sub-menu when the sub-trigger is activated', () => { const rendered = renderDevtools({ initialIsOpen: true }) fireEvent.keyDown(rendered.getByLabelText('Open settings menu'), { key: 'Enter', }) const themeTrigger = document.querySelector( '.tsqd-settings-menu-sub-trigger-theme', ) expect(themeTrigger).not.toBeNull() expect(themeTrigger).not.toBe( document.querySelector('.tsqd-settings-menu-sub-trigger-position'), ) fireEvent.keyDown(themeTrigger!, { key: 'ArrowRight' }) expect( document.querySelector('[aria-label="Theme preference"]'), ).not.toBeNull() }) it('should persist "theme_preference" when a theme radio item is selected', () => { const rendered = renderDevtools({ initialIsOpen: true }) fireEvent.keyDown(rendered.getByLabelText('Open settings menu'), { key: 'Enter', }) const themeTrigger = document.querySelector( '.tsqd-settings-menu-sub-trigger-theme', ) expect(themeTrigger).not.toBeNull() fireEvent.keyDown(themeTrigger!, { key: 'ArrowRight' }) const themeMenu = document.querySelector( '[aria-label="Theme preference"]', ) const lightItem = Array.from( themeMenu?.querySelectorAll('[role="menuitemradio"]') ?? [], ).find((el) => String(el.textContent).includes('Light')) expect(lightItem).toBeDefined() fireEvent.keyDown(lightItem!, { key: 'Enter' }) expect( localStorage.getItem('TanstackQueryDevtools.theme_preference'), ).toBe('light') }) it('should open "Hide disabled queries" sub-menu when the sub-trigger is activated', () => { const rendered = renderDevtools({ initialIsOpen: true }) fireEvent.keyDown(rendered.getByLabelText('Open settings menu'), { key: 'Enter', }) const hideTrigger = document.querySelector( '.tsqd-settings-menu-sub-trigger-disabled-queries', ) expect(hideTrigger).not.toBeNull() fireEvent.keyDown(hideTrigger!, { key: 'ArrowRight' }) expect( document.querySelector('[aria-label="Hide disabled queries setting"]'), ).not.toBeNull() }) it('should persist "hideDisabledQueries" when a hide-disabled radio item is selected', () => { const rendered = renderDevtools({ initialIsOpen: true }) fireEvent.keyDown(rendered.getByLabelText('Open settings menu'), { key: 'Enter', }) const hideTrigger = document.querySelector( '.tsqd-settings-menu-sub-trigger-disabled-queries', ) expect(hideTrigger).not.toBeNull() fireEvent.keyDown(hideTrigger!, { key: 'ArrowRight' }) const hideItem = document.querySelector( '.tsqd-settings-menu-position-btn-hide', ) expect(hideItem).not.toBeNull() fireEvent.keyDown(hideItem!, { key: 'Enter' }) expect( localStorage.getItem('TanstackQueryDevtools.hideDisabledQueries'), ).toBe('true') }) }) describe('text direction', () => { it('should render the floating devtools with "dir" set to "ltr"', () => { const rendered = renderDevtools({ initialIsOpen: true }) expect( rendered.container.querySelector('.tsqd-transitions-container'), ).toHaveAttribute('dir', 'ltr') }) it('should render the embedded panel with "dir" set to "ltr"', () => { const rendered = render(() => ( )) expect( rendered.container.querySelector('.tsqd-main-panel'), ).toHaveAttribute('dir', 'ltr') }) it('should render the settings menu with "dir" set to "ltr"', () => { const rendered = renderDevtools({ initialIsOpen: true }) fireEvent.keyDown(rendered.getByLabelText('Open settings menu'), { key: 'Enter', }) expect(document.querySelector('.tsqd-settings-menu')).toHaveAttribute( 'dir', 'ltr', ) }) it.each(['position', 'theme', 'disabled-queries'])( 'should render the "%s" sub-menu with "dir" set to "ltr"', (name) => { const rendered = renderDevtools({ initialIsOpen: true }) fireEvent.keyDown(rendered.getByLabelText('Open settings menu'), { key: 'Enter', }) const subTrigger = document.querySelector( `.tsqd-settings-menu-sub-trigger-${name}`, ) expect(subTrigger).not.toBeNull() fireEvent.keyDown(subTrigger!, { key: 'ArrowRight' }) expect( document.querySelector('.tsqd-settings-submenu'), ).toHaveAttribute('dir', 'ltr') }, ) it.each([ ['position', 'full'], ['theme', 'full'], ['disabled-queries', 'full'], ['theme', 'embedded'], ['disabled-queries', 'embedded'], ] as const)( 'should open the "%s" sub-menu with "ArrowRight" in the %s devtools when the browser language is RTL', (name, mode) => { const rendered = render(() => mode === 'full' ? ( ) : ( ), ) const language = vi .spyOn(navigator, 'language', 'get') .mockReturnValue('ar') window.dispatchEvent(new Event('languagechange')) try { fireEvent.keyDown(rendered.getByLabelText('Open settings menu'), { key: 'Enter', }) const subTrigger = document.querySelector( `.tsqd-settings-menu-sub-trigger-${name}`, ) expect(subTrigger).not.toBeNull() fireEvent.keyDown(subTrigger!, { key: 'ArrowRight' }) expect( document.querySelector('.tsqd-settings-submenu'), ).toHaveAttribute('dir', 'ltr') } finally { language.mockRestore() window.dispatchEvent(new Event('languagechange')) } }, ) }) describe('resize handle', () => { it('should increase height when "ArrowUp" is pressed on the resize handle in "bottom" position', () => { const rendered = renderDevtools( { position: 'bottom', initialIsOpen: true }, { 'TanstackQueryDevtools.height': '500' }, ) const handle = rendered.getByLabelText('Resize devtools panel') fireEvent.keyDown(handle, { key: 'ArrowUp' }) expect( Number(localStorage.getItem('TanstackQueryDevtools.height')), ).toBeGreaterThan(500) }) it('should decrease height when "ArrowDown" is pressed on the resize handle in "bottom" position', () => { const rendered = renderDevtools( { position: 'bottom', initialIsOpen: true }, { 'TanstackQueryDevtools.height': '500' }, ) const handle = rendered.getByLabelText('Resize devtools panel') fireEvent.keyDown(handle, { key: 'ArrowDown' }) // Assert the value exists before parsing — `Number(null)` is `0`, // which would falsely satisfy `toBeLessThan(500)` if the write was missing. const nextHeight = localStorage.getItem('TanstackQueryDevtools.height') expect(nextHeight).not.toBeNull() expect(Number(nextHeight)).toBeLessThan(500) }) it('should increase width when "ArrowLeft" is pressed on the resize handle in "right" position', () => { const rendered = renderDevtools( { position: 'right', initialIsOpen: true }, { 'TanstackQueryDevtools.width': '500' }, ) const handle = rendered.getByLabelText('Resize devtools panel') fireEvent.keyDown(handle, { key: 'ArrowLeft' }) expect( Number(localStorage.getItem('TanstackQueryDevtools.width')), ).toBeGreaterThan(500) }) it('should decrease width when "ArrowRight" is pressed on the resize handle in "right" position', () => { const rendered = renderDevtools( { position: 'right', initialIsOpen: true }, { 'TanstackQueryDevtools.width': '500' }, ) const handle = rendered.getByLabelText('Resize devtools panel') fireEvent.keyDown(handle, { key: 'ArrowRight' }) const nextWidth = localStorage.getItem('TanstackQueryDevtools.width') expect(nextWidth).not.toBeNull() expect(Number(nextWidth)).toBeLessThan(500) }) it('should increase height while dragging up in "bottom" position', () => { const initialHeight = 500 const rendered = renderDevtools( { position: 'bottom', initialIsOpen: true }, { 'TanstackQueryDevtools.height': String(initialHeight) }, ) const handle = rendered.getByLabelText('Resize devtools panel') // jsdom returns zeros for `getBoundingClientRect`; stub the panel size so // that drag math starts from `initialHeight` instead of 0. // Only `height` is read by the production code; other fields are unused. const panel = handle.parentElement expect(panel).toBeInstanceOf(HTMLElement) vi.spyOn(panel!, 'getBoundingClientRect').mockReturnValue({ height: initialHeight, width: 0, x: 0, y: 0, top: 0, right: 0, bottom: 0, left: 0, toJSON: () => ({}), }) // Move the cursor up by 50px (`clientY` 100 → 50), which adds 50px to the // drag base of `initialHeight`. fireEvent.mouseDown(handle, { clientX: 0, clientY: 100 }) fireEvent( document, new MouseEvent('mousemove', { clientX: 0, clientY: 50 }), ) fireEvent(document, new MouseEvent('mouseup')) expect( Number(localStorage.getItem('TanstackQueryDevtools.height')), ).toBeGreaterThan(initialHeight) }) it('should increase width while dragging left in "right" position', () => { const initialWidth = 500 const rendered = renderDevtools( { position: 'right', initialIsOpen: true }, { 'TanstackQueryDevtools.width': String(initialWidth) }, ) const handle = rendered.getByLabelText('Resize devtools panel') // `width` is read twice during drag: once as the base size, and again to // detect when the panel hits its minimum. Returning the same value both // times keeps the "minimum reached" branch from firing. const panel = handle.parentElement expect(panel).toBeInstanceOf(HTMLElement) vi.spyOn(panel!, 'getBoundingClientRect').mockReturnValue({ height: 0, width: initialWidth, x: 0, y: 0, top: 0, right: 0, bottom: 0, left: 0, toJSON: () => ({}), }) // Move the cursor left by 50px (`clientX` 100 → 50); in `right` position, // moving left grows the panel by 50px from the drag base of `initialWidth`. fireEvent.mouseDown(handle, { clientX: 100, clientY: 0 }) fireEvent( document, new MouseEvent('mousemove', { clientX: 50, clientY: 0 }), ) fireEvent(document, new MouseEvent('mouseup')) expect( Number(localStorage.getItem('TanstackQueryDevtools.width')), ).toBeGreaterThan(initialWidth) }) it('should clamp the width to the minimum when dragging shrinks the panel below the minimum width', () => { const initialWidth = 200 const rendered = renderDevtools( { position: 'left', initialIsOpen: true }, { 'TanstackQueryDevtools.width': String(initialWidth) }, ) const handle = rendered.getByLabelText('Resize devtools panel') const panel = handle.parentElement expect(panel).toBeInstanceOf(HTMLElement) // `width` is read twice during drag: once as the base size, and again // after the clamp to detect when the panel has hit its minimum. The // first call returns `initialWidth`; the second returns `0` so the // `localStore.width < newWidth` restore branch stays inactive and only // the `newSize < minWidth` clamp is observed. const getBoundingClientRect = vi .spyOn(panel!, 'getBoundingClientRect') .mockReturnValueOnce({ height: 0, width: initialWidth, x: 0, y: 0, top: 0, right: 0, bottom: 0, left: 0, toJSON: () => ({}), }) getBoundingClientRect.mockReturnValue({ height: 0, width: 0, x: 0, y: 0, top: 0, right: 0, bottom: 0, left: 0, toJSON: () => ({}), }) // In `left` position, dragging the cursor left (`clientX` 100 → 0) // shrinks the panel by 100px, which lands well under the 192px minimum. fireEvent.mouseDown(handle, { clientX: 100, clientY: 0 }) fireEvent( document, new MouseEvent('mousemove', { clientX: 0, clientY: 0 }), ) fireEvent(document, new MouseEvent('mouseup')) expect(Number(localStorage.getItem('TanstackQueryDevtools.width'))).toBe( 192, ) }) it('should restore "width" to the rendered minimum when the panel is dragged below its content width', () => { const initialWidth = 400 // The panel uses `min-width: min-content`, so the rendered width may // exceed the 192px `minWidth` constant when its children are wider; any // value > 192 here triggers the `localStore.width < newWidth` restore // branch. const renderedMinWidth = 250 const rendered = renderDevtools( { position: 'left', initialIsOpen: true }, { 'TanstackQueryDevtools.width': String(initialWidth) }, ) const handle = rendered.getByLabelText('Resize devtools panel') const panel = handle.parentElement expect(panel).toBeInstanceOf(HTMLElement) const getBoundingClientRect = vi .spyOn(panel!, 'getBoundingClientRect') .mockReturnValueOnce({ height: 0, width: initialWidth, x: 0, y: 0, top: 0, right: 0, bottom: 0, left: 0, toJSON: () => ({}), }) getBoundingClientRect.mockReturnValue({ height: 0, width: renderedMinWidth, x: 0, y: 0, top: 0, right: 0, bottom: 0, left: 0, toJSON: () => ({}), }) // Drag 300px left shrinks the panel to 100 — below `minWidth`, so the // clamp + restore branches both fire. fireEvent.mouseDown(handle, { clientX: 300, clientY: 0 }) fireEvent( document, new MouseEvent('mousemove', { clientX: 0, clientY: 0 }), ) fireEvent(document, new MouseEvent('mouseup')) expect(Number(localStorage.getItem('TanstackQueryDevtools.width'))).toBe( renderedMinWidth, ) }) it('should close the query details panel when dragging shrinks the panel below the minimum height', () => { queryClient.setQueryData(['shrink-below-min-height'], [{ id: 1 }]) const rendered = renderDevtools({ position: 'bottom', initialIsOpen: true, }) // Open the query details so `selectedQueryHash` is set. fireEvent.click( rendered.getByLabelText(/Query key \["shrink-below-min-height"\]/), ) expect(rendered.getByText('Query Details')).toBeInTheDocument() const handle = rendered.getByLabelText('Resize devtools panel') const panel = handle.parentElement expect(panel).toBeInstanceOf(HTMLElement) // Stub the base size to a value just above the 56px (`3.5rem`) minimum so // a small downward drag pushes `newSize` below `minHeight` and triggers // the clamp branch that also resets `selectedQueryHash`. vi.spyOn(panel!, 'getBoundingClientRect').mockReturnValue({ height: 60, width: 0, x: 0, y: 0, top: 0, right: 0, bottom: 0, left: 0, toJSON: () => ({}), }) // In `bottom` position, dragging the cursor down (`clientY` 100 → 200) // shrinks the panel by 100px, which is well under the 56px minimum. fireEvent.mouseDown(handle, { clientX: 0, clientY: 100 }) fireEvent( document, new MouseEvent('mousemove', { clientX: 0, clientY: 200 }), ) fireEvent(document, new MouseEvent('mouseup')) expect(rendered.queryByText('Query Details')).not.toBeInTheDocument() }) }) describe('online toggle', () => { it('should swap the toggle label after the offline button is clicked', () => { const rendered = renderDevtools({ initialIsOpen: true }) fireEvent.click(rendered.getByLabelText('Mock offline behavior')) expect( rendered.getByLabelText('Unset offline mocking behavior'), ).toBeInTheDocument() }) }) describe('logo close', () => { it('should hide the panel when the TanStack logo is clicked', () => { const rendered = renderDevtools({ initialIsOpen: true }) fireEvent.click(rendered.getByLabelText('Close Tanstack query devtools')) expect( rendered.queryByLabelText('Tanstack query devtools'), ).not.toBeInTheDocument() }) }) })