From 5003d9f57e398cd12a22314dc8d576cadf35a20a Mon Sep 17 00:00:00 2001 From: Yahya Fakhroji Date: Thu, 19 Nov 2026 14:41:08 +0700 Subject: [PATCH 1/7] test(place-autocomplete): cover search and selection and gate re-exported components The coverage gate only read exports whose source sits under src/components, so Map and PlaceAutocomplete, re-exported through src/exports/map.ts, were never checked and PlaceAutocomplete had no tests. The gate now follows src/exports re-exports, and new tests cover searching, keyboard selection, Escape, the empty and error states, and cancelling a stale search. --- .../scripts/check-component-coverage.mjs | 32 ++++-- .../__tests__/place-autocomplete.test.tsx | 104 ++++++++++++++++++ 2 files changed, 128 insertions(+), 8 deletions(-) create mode 100644 packages/datum-ui/src/components/base/place-autocomplete/__tests__/place-autocomplete.test.tsx diff --git a/packages/datum-ui/scripts/check-component-coverage.mjs b/packages/datum-ui/scripts/check-component-coverage.mjs index f93c5ef3..4ec48fae 100644 --- a/packages/datum-ui/scripts/check-component-coverage.mjs +++ b/packages/datum-ui/scripts/check-component-coverage.mjs @@ -44,6 +44,25 @@ function walk(dir) { return out } +/** + * The [section, name] pairs an export's source publishes. A source under + * src/components/ is one component; an aggregate entry under src/exports/ + * (e.g. ./map re-exports Map and PlaceAutocomplete) publishes every component + * it re-exports with `export * from '../components/
/'`. + */ +function componentsOf(source) { + const direct = source.match(/^\.\/src\/components\/(base|features)\/([^/]+)\//) + if (direct) { + return [[direct[1], direct[2]]] + } + if (!/^\.\/src\/exports\/[^/]+\.ts$/.test(source)) { + return [] + } + const text = fs.readFileSync(path.join(PKG_ROOT, source), 'utf8') + return [...text.matchAll(/export \* from '\.\.\/components\/(base|features)\/([^/']+)'/g)] + .map(([, section, name]) => [section, name]) +} + /** Public component exports resolved to { key, name, dir }. */ function collectComponents() { const pkg = JSON.parse(fs.readFileSync(path.join(PKG_ROOT, 'package.json'), 'utf8')) @@ -53,14 +72,11 @@ function collectComponents() { if (typeof source !== 'string') { continue } - const m = source.match(/^\.\/src\/components\/(base|features)\/([^/]+)\//) - if (!m) { - continue - } - const [, section, name] = m - const key = `${section}/${name}` - if (!seen.has(key)) { - seen.set(key, { key, name, dir: path.join(PKG_ROOT, 'src', 'components', section, name) }) + for (const [section, name] of componentsOf(source)) { + const key = `${section}/${name}` + if (!seen.has(key)) { + seen.set(key, { key, name, dir: path.join(PKG_ROOT, 'src', 'components', section, name) }) + } } } return [...seen.values()].sort((a, b) => a.key.localeCompare(b.key)) diff --git a/packages/datum-ui/src/components/base/place-autocomplete/__tests__/place-autocomplete.test.tsx b/packages/datum-ui/src/components/base/place-autocomplete/__tests__/place-autocomplete.test.tsx new file mode 100644 index 00000000..1b4d7b75 --- /dev/null +++ b/packages/datum-ui/src/components/base/place-autocomplete/__tests__/place-autocomplete.test.tsx @@ -0,0 +1,104 @@ +/// +import { render, screen, waitFor } from '@testing-library/react' +import userEvent from '@testing-library/user-event' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { PlaceAutocomplete } from '../index' + +function feature(name: string, osmId: number) { + return { + type: 'Feature', + geometry: { type: 'Point', coordinates: [13.4, 52.5] }, + properties: { osm_id: osmId, osm_type: 'N', osm_key: 'place', osm_value: 'city', type: 'city', name, country: 'Germany' }, + } +} + +function respond(features: ReturnType[]) { + return new Response(JSON.stringify({ type: 'FeatureCollection', features }), { status: 200 }) +} + +afterEach(() => vi.unstubAllGlobals()) + +describe('placeAutocomplete', () => { + it('searches after typing and lists the results', async () => { + const fetchFn = vi.fn((_url: string) => Promise.resolve(respond([feature('Berlin', 1), feature('Bern', 2)]))) + vi.stubGlobal('fetch', fetchFn) + const onResultsChange = vi.fn() + render() + await userEvent.type(screen.getByPlaceholderText('Search'), 'Berlin') + expect(await screen.findByRole('option', { name: /Berlin/ })).toBeInTheDocument() + expect(screen.getByRole('option', { name: /Bern/ })).toBeInTheDocument() + expect(String(fetchFn.mock.calls.at(-1)?.[0])).toContain('Berlin') + await waitFor(() => expect(onResultsChange).toHaveBeenLastCalledWith(expect.arrayContaining([expect.objectContaining({ properties: expect.objectContaining({ name: 'Berlin' }) })]))) + }) + + it('selects a result with the arrow keys and Enter, then closes the list', async () => { + vi.stubGlobal('fetch', vi.fn(() => Promise.resolve(respond([feature('Berlin', 1), feature('Bern', 2)])))) + const onPlaceSelect = vi.fn() + render() + const input = screen.getByPlaceholderText('Search') + await userEvent.type(input, 'Ber') + await screen.findByRole('option', { name: /Berlin/ }) + await userEvent.keyboard('{ArrowDown}{Enter}') + expect(onPlaceSelect).toHaveBeenCalledTimes(1) + expect(onPlaceSelect.mock.calls[0]![0].properties.name).toMatch(/Bern/) + await waitFor(() => expect(screen.queryByRole('option')).toBeNull()) + }) + + it('closes the list on Escape without selecting', async () => { + vi.stubGlobal('fetch', vi.fn(() => Promise.resolve(respond([feature('Berlin', 1)])))) + const onPlaceSelect = vi.fn() + render() + await userEvent.type(screen.getByPlaceholderText('Search'), 'Berlin') + await screen.findByRole('option', { name: /Berlin/ }) + await userEvent.keyboard('{Escape}') + await waitFor(() => expect(screen.queryByRole('option')).toBeNull()) + expect(onPlaceSelect).not.toHaveBeenCalled() + }) + + it('sends no request for a blank query', async () => { + const fetchFn = vi.fn() + vi.stubGlobal('fetch', fetchFn) + render() + await userEvent.type(screen.getByPlaceholderText('Search'), ' ') + await new Promise(resolve => setTimeout(resolve, 20)) + expect(fetchFn).not.toHaveBeenCalled() + }) + + it('shows the empty state when nothing matches', async () => { + vi.stubGlobal('fetch', vi.fn(() => Promise.resolve(respond([])))) + render() + await userEvent.type(screen.getByPlaceholderText('Search'), 'Nowhere') + await waitFor(() => expect(screen.getByText(/can't find/i)).toBeInTheDocument()) + }) + + it('shows the error state when the request fails', async () => { + vi.stubGlobal('fetch', vi.fn().mockRejectedValue(new Error('network down'))) + render() + await userEvent.type(screen.getByPlaceholderText('Search'), 'Berlin') + expect(await screen.findByText(/network down/)).toBeInTheDocument() + }) + + it('cancels an earlier search so its late response never replaces the latest results', async () => { + let resolveFirst: (value: Response) => void = () => {} + let firstSignal: AbortSignal | undefined + // Like a real fetch, the first request rejects once its signal aborts. + const fetchFn = vi.fn() + .mockImplementationOnce((_url: string, init: RequestInit) => new Promise((resolve, reject) => { + resolveFirst = resolve + firstSignal = init.signal ?? undefined + firstSignal?.addEventListener('abort', () => reject(new DOMException('Aborted', 'AbortError'))) + })) + .mockImplementation(() => Promise.resolve(respond([feature('Berlin', 1)]))) + vi.stubGlobal('fetch', fetchFn) + render() + const input = screen.getByPlaceholderText('Search') + await userEvent.type(input, 'Ber') + await waitFor(() => expect(fetchFn).toHaveBeenCalledTimes(1)) + await userEvent.type(input, 'lin') + expect(await screen.findByRole('option', { name: /Berlin/ })).toBeInTheDocument() + expect(firstSignal?.aborted).toBe(true) + resolveFirst(respond([feature('Bermuda', 9)])) + await new Promise(resolve => setTimeout(resolve, 20)) + expect(screen.queryByRole('option', { name: /Bermuda/ })).toBeNull() + }) +}) From f9da44d3384c8a317d54b2ea1a42be9f3de5aac9 Mon Sep 17 00:00:00 2001 From: Yahya Fakhroji Date: Thu, 19 Nov 2026 14:43:26 +0700 Subject: [PATCH 2/7] test(map): cover rendering and the map controls Map's only test covered the theme-aware tile layer. A smoke test now mounts the real lazy-loaded Leaflet map, and the zoom, locate and fullscreen controls are tested against a fake Leaflet map: zooming, disabling at the zoom limits, locating and reporting the result or the error, and following the map's fullscreen events. --- .../base/map/__tests__/map-controls.test.tsx | 122 ++++++++++++++++++ .../base/map/__tests__/map.test.tsx | 21 +++ 2 files changed, 143 insertions(+) create mode 100644 packages/datum-ui/src/components/base/map/__tests__/map-controls.test.tsx create mode 100644 packages/datum-ui/src/components/base/map/__tests__/map.test.tsx diff --git a/packages/datum-ui/src/components/base/map/__tests__/map-controls.test.tsx b/packages/datum-ui/src/components/base/map/__tests__/map-controls.test.tsx new file mode 100644 index 00000000..1ae7d560 --- /dev/null +++ b/packages/datum-ui/src/components/base/map/__tests__/map-controls.test.tsx @@ -0,0 +1,122 @@ +/// +import { act, render, screen } from '@testing-library/react' +import userEvent from '@testing-library/user-event' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { MapFullscreenControl, MapLocateControl, MapZoomControl } from '../index' + +// A Leaflet map stand-in: the controls only call these methods and listen to +// these events, so the tests drive them directly without a real map. +const handlers = new Map void>() +const fakeMap = { + zoom: 10, + getZoom: () => fakeMap.zoom, + getMaxZoom: () => 18, + getMinZoom: () => 0, + zoomIn: vi.fn(), + zoomOut: vi.fn(), + locate: vi.fn(), + stopLocate: vi.fn(), + toggleFullscreen: vi.fn(), + on: vi.fn((event: string, handler: (event?: unknown) => void) => { + handlers.set(event, handler) + }), + off: vi.fn(), +} +let zoomEvents: Record void> = {} + +class FakeFullScreenControl { + addTo() { + return this + } + + getContainer() { + return document.createElement('div') + } + + remove() {} +} + +// `shared` and `hooks` are modules the @repo/shadcn exports map does not +// expose, so they are mocked by path, as map-tile-layer.test.tsx does. +vi.mock('../../../../../../shadcn/ui/map/shared', () => ({ + _useMap: () => fakeMap, + _useMapEvents: (events: Record void>) => { + zoomEvents = events + return fakeMap + }, +})) +vi.mock('../../../../../../shadcn/ui/map/hooks', async importOriginal => ({ + ...(await importOriginal>()), + useLeaflet: () => ({ + L: { + Control: { FullScreen: FakeFullScreenControl }, + // MapControlContainer stops clicks and scrolls on a control reaching the map. + DomEvent: { disableClickPropagation: () => {}, disableScrollPropagation: () => {} }, + // The locate control marks the found location with a div icon. + divIcon: (options: unknown) => options, + }, + }), +})) + +beforeEach(() => { + vi.clearAllMocks() + handlers.clear() + fakeMap.zoom = 10 +}) + +describe('mapZoomControl', () => { + it('zooms in and out', async () => { + render() + await userEvent.click(screen.getByRole('button', { name: /zoom in/i })) + await userEvent.click(screen.getByRole('button', { name: /zoom out/i })) + expect(fakeMap.zoomIn).toHaveBeenCalledTimes(1) + expect(fakeMap.zoomOut).toHaveBeenCalledTimes(1) + }) + + it('disables zoom in at the maximum zoom', () => { + fakeMap.zoom = 18 + render() + expect(screen.getByRole('button', { name: /zoom in/i })).toBeDisabled() + expect(screen.getByRole('button', { name: /zoom out/i })).toBeEnabled() + }) + + it('follows the map when its zoom changes', () => { + render() + fakeMap.zoom = 0 + act(() => zoomEvents.zoomend?.()) + expect(screen.getByRole('button', { name: /zoom out/i })).toBeDisabled() + }) +}) + +describe('mapLocateControl', () => { + it('asks the map to locate the person and reports the location', async () => { + const onLocationFound = vi.fn() + render() + await userEvent.click(screen.getByRole('button')) + expect(fakeMap.locate).toHaveBeenCalledWith(expect.objectContaining({ setView: true, maxZoom: 18 })) + const found = { latlng: { lat: 52.5, lng: 13.4 }, accuracy: 10 } + act(() => handlers.get('locationfound')?.(found)) + expect(onLocationFound).toHaveBeenCalledWith(found) + }) + + it('reports a location error', async () => { + const onLocationError = vi.fn() + render() + await userEvent.click(screen.getByRole('button')) + const error = { message: 'denied', code: 1 } + act(() => handlers.get('locationerror')?.(error)) + expect(onLocationError).toHaveBeenCalledWith(error) + }) +}) + +describe('mapFullscreenControl', () => { + it('toggles fullscreen and follows the map\'s fullscreen events', async () => { + render() + await userEvent.click(screen.getByRole('button', { name: 'Enter fullscreen' })) + expect(fakeMap.toggleFullscreen).toHaveBeenCalledTimes(1) + act(() => handlers.get('enterFullscreen')?.()) + expect(screen.getByRole('button', { name: 'Exit fullscreen' })).toBeInTheDocument() + act(() => handlers.get('exitFullscreen')?.()) + expect(screen.getByRole('button', { name: 'Enter fullscreen' })).toBeInTheDocument() + }) +}) diff --git a/packages/datum-ui/src/components/base/map/__tests__/map.test.tsx b/packages/datum-ui/src/components/base/map/__tests__/map.test.tsx new file mode 100644 index 00000000..761ae289 --- /dev/null +++ b/packages/datum-ui/src/components/base/map/__tests__/map.test.tsx @@ -0,0 +1,21 @@ +/// +import { render, screen } from '@testing-library/react' +import { describe, expect, it } from 'vitest' +import { Map } from '../index' + +// A smoke test with the real lazy modules: Leaflet renders into jsdom's DOM, +// so the map mounts without a browser. Controls and layers are tested with a +// fake map in map-controls.test.tsx and map-tile-layer.test.tsx. +describe('map', () => { + it('loads Leaflet and renders the map with its children', async () => { + const { container } = render( + +
+ , + ) + expect(await screen.findByTestId('map-child', {}, { timeout: 5000 })).toBeInTheDocument() + const mapElement = container.querySelector('.leaflet-container') + expect(mapElement).not.toBeNull() + expect(mapElement).toHaveClass('min-h-96') + }) +}) From 6dfdb845f65a905154bb5da1a9239f400b962ff1 Mon Sep 17 00:00:00 2001 From: Yahya Fakhroji Date: Thu, 19 Nov 2026 14:44:52 +0700 Subject: [PATCH 3/7] test(sidebar): cover toggling, the shortcut and the mobile sheet Sidebar had no tests and the coverage baseline exempted it. New tests cover the trigger, defaultOpen and controlled open, the Cmd+B and Ctrl+B shortcut (a bare b, including one typed in the sidebar input, does nothing), the state cookie, the mobile sheet, and active and disabled menu items. Sidebar leaves the coverage baseline. --- .../scripts/component-coverage-baseline.json | 3 - .../base/sidebar/__tests__/sidebar.test.tsx | 108 ++++++++++++++++++ 2 files changed, 108 insertions(+), 3 deletions(-) create mode 100644 packages/datum-ui/src/components/base/sidebar/__tests__/sidebar.test.tsx diff --git a/packages/datum-ui/scripts/component-coverage-baseline.json b/packages/datum-ui/scripts/component-coverage-baseline.json index 58facd88..2c5b4b89 100644 --- a/packages/datum-ui/scripts/component-coverage-baseline.json +++ b/packages/datum-ui/scripts/component-coverage-baseline.json @@ -29,9 +29,6 @@ "base/separator": [ "test" ], - "base/sidebar": [ - "test" - ], "base/skeleton": [ "test" ], diff --git a/packages/datum-ui/src/components/base/sidebar/__tests__/sidebar.test.tsx b/packages/datum-ui/src/components/base/sidebar/__tests__/sidebar.test.tsx new file mode 100644 index 00000000..2d1fb58f --- /dev/null +++ b/packages/datum-ui/src/components/base/sidebar/__tests__/sidebar.test.tsx @@ -0,0 +1,108 @@ +/// +import { fireEvent, render, screen } from '@testing-library/react' +import userEvent from '@testing-library/user-event' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { SidebarInput, SidebarMenu, SidebarMenuButton, SidebarMenuItem, SidebarProvider, SidebarTrigger, useSidebar } from '../index' + +const viewport = { mobile: false } +vi.mock('@repo/shadcn/hooks/use-mobile', () => ({ useIsMobile: () => viewport.mobile })) + +/** Shows the sidebar state the provider exposes. */ +function Probe() { + const { state, openMobile } = useSidebar() + return +} + +function renderSidebar(props: Partial> = {}) { + return render( + + + + + , + ) +} + +const state = () => screen.getByTestId('probe').getAttribute('data-state') + +beforeEach(() => { + viewport.mobile = false + // Below the lg breakpoint the provider starts collapsed; test at desktop width. + Object.defineProperty(window, 'innerWidth', { configurable: true, value: 1440 }) + document.cookie = 'sidebar_state=; max-age=0; path=/' +}) + +afterEach(() => vi.restoreAllMocks()) + +describe('sidebarProvider', () => { + it('toggles between expanded and collapsed with the trigger', async () => { + renderSidebar() + expect(state()).toBe('expanded') + await userEvent.click(screen.getByRole('button', { name: 'Toggle Sidebar' })) + expect(state()).toBe('collapsed') + await userEvent.click(screen.getByRole('button', { name: 'Toggle Sidebar' })) + expect(state()).toBe('expanded') + }) + + it('starts collapsed with defaultOpen false', () => { + renderSidebar({ defaultOpen: false }) + expect(state()).toBe('collapsed') + }) + + it('reports changes through onOpenChange when controlled', async () => { + const onOpenChange = vi.fn() + renderSidebar({ open: true, onOpenChange }) + await userEvent.click(screen.getByRole('button', { name: 'Toggle Sidebar' })) + expect(onOpenChange).toHaveBeenCalledWith(false) + expect(state()).toBe('expanded') + }) + + it('toggles with Cmd+B and Ctrl+B', () => { + renderSidebar() + fireEvent.keyDown(window, { key: 'b', metaKey: true }) + expect(state()).toBe('collapsed') + fireEvent.keyDown(window, { key: 'b', ctrlKey: true }) + expect(state()).toBe('expanded') + }) + + it('ignores a bare b, including one typed in the sidebar input', async () => { + renderSidebar() + fireEvent.keyDown(window, { key: 'b' }) + await userEvent.type(screen.getByPlaceholderText('Filter'), 'b') + expect(state()).toBe('expanded') + }) + + it('remembers the state in a cookie', async () => { + renderSidebar() + await userEvent.click(screen.getByRole('button', { name: 'Toggle Sidebar' })) + expect(document.cookie).toContain('sidebar_state=false') + }) + + it('opens the mobile sheet instead of collapsing on a phone', async () => { + viewport.mobile = true + renderSidebar() + await userEvent.click(screen.getByRole('button', { name: 'Toggle Sidebar' })) + expect(screen.getByTestId('probe')).toHaveAttribute('data-open-mobile', 'true') + }) +}) + +describe('sidebarMenuButton', () => { + it('marks the active item and does not run a disabled one', async () => { + const onClick = vi.fn() + render( + + + + Projects + + + Billing + + + , + ) + expect(screen.getByRole('button', { name: 'Projects' })).toHaveAttribute('data-active', 'true') + await userEvent.click(screen.getByRole('button', { name: 'Billing' })) + expect(onClick).not.toHaveBeenCalled() + }) +}) From 4e87a03c852de4e822d1d0e1e285960c2f945e0c Mon Sep 17 00:00:00 2001 From: Yahya Fakhroji Date: Thu, 19 Nov 2026 14:47:03 +0700 Subject: [PATCH 4/7] test(stepper): cover navigation, step states and keyboard focus Stepper had no tests and the coverage baseline exempted it. New tests cover moving next and back, staying on the first and last steps, the current, completed and upcoming step states, disabled steps that cannot be clicked, and the helpers for step state, DOM ids and arrow-key focus. Stepper leaves the coverage baseline. --- .../scripts/component-coverage-baseline.json | 3 - .../stepper/__tests__/stepper.test.tsx | 118 ++++++++++++++++++ 2 files changed, 118 insertions(+), 3 deletions(-) create mode 100644 packages/datum-ui/src/components/features/stepper/__tests__/stepper.test.tsx diff --git a/packages/datum-ui/scripts/component-coverage-baseline.json b/packages/datum-ui/scripts/component-coverage-baseline.json index 2c5b4b89..fe3585a5 100644 --- a/packages/datum-ui/scripts/component-coverage-baseline.json +++ b/packages/datum-ui/scripts/component-coverage-baseline.json @@ -43,8 +43,5 @@ ], "features/nprogress": [ "test" - ], - "features/stepper": [ - "test" ] } diff --git a/packages/datum-ui/src/components/features/stepper/__tests__/stepper.test.tsx b/packages/datum-ui/src/components/features/stepper/__tests__/stepper.test.tsx new file mode 100644 index 00000000..46248124 --- /dev/null +++ b/packages/datum-ui/src/components/features/stepper/__tests__/stepper.test.tsx @@ -0,0 +1,118 @@ +/// +import type * as Stepperize from '@stepperize/react' +import { render, screen } from '@testing-library/react' +import userEvent from '@testing-library/user-event' +import { describe, expect, it } from 'vitest' +import { defineStepper } from '../index' +import { getStepState, onStepKeyDown, stepDomId } from '../utils' + +const { Stepper, steps } = defineStepper( + { id: 'account', title: 'Account' }, + { id: 'billing', title: 'Billing' }, + { id: 'review', title: 'Review' }, +) + +function renderStepper({ disabledStep }: { disabledStep?: string } = {}) { + return render( + + {({ methods }) => ( + <> + + {steps.map(step => ( + methods.goTo(step.id)}> + {step.title} + + ))} + + {methods.current.id} + + + + + + )} + , + ) +} + +const current = () => screen.getByTestId('current').textContent + +describe('stepper', () => { + it('starts on the first step and moves next and back', async () => { + renderStepper() + expect(current()).toBe('account') + await userEvent.click(screen.getByRole('button', { name: 'Next' })) + expect(current()).toBe('billing') + await userEvent.click(screen.getByRole('button', { name: 'Back' })) + expect(current()).toBe('account') + }) + + it('does not move before the first step or past the last', async () => { + renderStepper() + await userEvent.click(screen.getByRole('button', { name: 'Back' })) + expect(current()).toBe('account') + await userEvent.click(screen.getByRole('button', { name: 'Next' })) + await userEvent.click(screen.getByRole('button', { name: 'Next' })) + await userEvent.click(screen.getByRole('button', { name: 'Next' })) + expect(current()).toBe('review') + }) + + it('marks the current step and the completed ones', async () => { + renderStepper() + await userEvent.click(screen.getByRole('button', { name: 'Next' })) + // Each step is an
  • holding its tab button and its title. + const stepItem = (title: string) => screen.getByText(title).closest('li')! + const stateOf = (title: string) => stepItem(title).getAttribute('data-state') + expect(stepItem('Billing').querySelector('[role="tab"]')).toHaveAttribute('aria-current', 'step') + expect(stateOf('Account')).toBe('completed') + expect(stateOf('Billing')).toBe('active') + expect(stateOf('Review')).toBe('inactive') + }) + + it('does not reach a disabled step by clicking it', async () => { + renderStepper({ disabledStep: 'review' }) + const reviewTab = screen.getByText('Review').closest('li')!.querySelector('[role="tab"]')! + expect(reviewTab).toBeDisabled() + await userEvent.click(reviewTab) + expect(current()).toBe('account') + // An enabled step is reachable the same way, so the check above is meaningful. + await userEvent.click(screen.getByText('Billing').closest('li')!.querySelector('[role="tab"]')!) + expect(current()).toBe('billing') + }) +}) + +describe('stepper helpers', () => { + it('derives each step\'s state from the current index', () => { + expect(getStepState(1, 0)).toBe('completed') + expect(getStepState(1, 1)).toBe('active') + expect(getStepState(1, 2)).toBe('inactive') + }) + + it('builds a stable DOM id per instance and step', () => { + expect(stepDomId('s1-', 'billing')).toBe(stepDomId('s1-', 'billing')) + expect(stepDomId('s1-', 'billing')).not.toBe(stepDomId('s2-', 'billing')) + }) + + it('moves focus with the arrow keys, and only forward to a reachable step', () => { + const make = (id: string, state: string) => { + const wrapper = document.createElement('div') + wrapper.setAttribute('data-state', state) + const button = document.createElement('button') + button.id = stepDomId('t-', id) + wrapper.append(button) + document.body.append(wrapper) + return button + } + const prev = make('a', 'completed') + const next = make('c', 'inactive') + const key = (k: string) => ({ key: k }) as React.KeyboardEvent + const step = (id: string) => ({ id }) as Stepperize.Step + onStepKeyDown(key('ArrowRight'), step('c'), step('a'), 't-') + expect(document.activeElement).not.toBe(next) + onStepKeyDown(key('ArrowLeft'), step('c'), step('a'), 't-') + expect(document.activeElement).toBe(prev) + next.parentElement!.setAttribute('data-state', 'active') + onStepKeyDown(key('ArrowDown'), step('c'), step('a'), 't-') + expect(document.activeElement).toBe(next) + }) +}) From 490d315a236505285449baf7242139510628f8f1 Mon Sep 17 00:00:00 2001 From: Yahya Fakhroji Date: Thu, 19 Nov 2026 14:48:05 +0700 Subject: [PATCH 5/7] test(task-queue): cover the queue and scope hooks useTaskQueue and the scope helpers had no tests. New tests cover the error outside a provider, listing, cancelling, filtering and dismissing tasks, picking the project, org or global scope, matching tasks to the current scope, the context labels, and when the task list shows those labels. --- .../task-queue/hooks/__tests__/hooks.test.tsx | 113 ++++++++++++++++++ 1 file changed, 113 insertions(+) create mode 100644 packages/datum-ui/src/components/features/task-queue/hooks/__tests__/hooks.test.tsx diff --git a/packages/datum-ui/src/components/features/task-queue/hooks/__tests__/hooks.test.tsx b/packages/datum-ui/src/components/features/task-queue/hooks/__tests__/hooks.test.tsx new file mode 100644 index 00000000..74ca0343 --- /dev/null +++ b/packages/datum-ui/src/components/features/task-queue/hooks/__tests__/hooks.test.tsx @@ -0,0 +1,113 @@ +/// +import type { ReactNode } from 'react' +import type { Task } from '../../types' +import { act, renderHook, waitFor } from '@testing-library/react' +import { describe, expect, it } from 'vitest' +import { MemoryTaskStorage } from '../../engine/storage/memory-storage' +import { TaskQueueProvider } from '../../provider/task-queue-provider' +import { createOrgMetadata, createProjectMetadata, createUserMetadata } from '../../utils' +import { useTaskQueue } from '../use-task-queue' +import { getContextLabel, matchesCurrentScope, useCurrentScope, useTasksWithLabels } from '../use-task-scope' + +function wrapper({ children }: { children: ReactNode }) { + return {children} +} + +const org = { id: 'org-1', name: 'Acme' } +const project = { id: 'proj-1', name: 'Web' } + +describe('useTaskQueue', () => { + it('throws outside a TaskQueueProvider', () => { + expect(() => renderHook(() => useTaskQueue())).toThrow('useTaskQueue must be used within a TaskQueueProvider') + }) + + it('lists an enqueued task and cancels it', async () => { + const { result } = renderHook(() => useTaskQueue(), { wrapper }) + let id = '' + act(() => { + id = result.current.enqueue({ + title: 'Slow task', + cancelable: true, + processor: ctx => new Promise((resolve) => { + const timer = setInterval(() => { + if (ctx.cancelled) { + clearInterval(timer) + resolve() + } + }, 5) + }), + }).id + }) + await waitFor(() => expect(result.current.tasks.map(task => task.title)).toContain('Slow task')) + act(() => result.current.cancel(id)) + await waitFor(() => expect(result.current.tasks.find(task => task.id === id)?.status).toBe('cancelled')) + }) + + it('filters by status and dismisses a finished task', async () => { + const { result } = renderHook(() => useTaskQueue({ status: 'completed' }), { wrapper }) + let id = '' + act(() => { + id = result.current.enqueue({ title: 'Quick task', processor: async () => {} }).id + }) + await waitFor(() => expect(result.current.tasks.map(task => task.id)).toEqual([id])) + act(() => result.current.dismiss(id)) + await waitFor(() => expect(result.current.tasks).toHaveLength(0)) + }) +}) + +describe('useCurrentScope', () => { + it('prefers the project, then the org, then the global scope', () => { + expect(renderHook(() => useCurrentScope({ projectId: 'proj-1', orgId: 'org-1' })).result.current) + .toEqual({ type: 'project', projectId: 'proj-1', orgId: 'org-1' }) + expect(renderHook(() => useCurrentScope({ orgId: 'org-1' })).result.current).toEqual({ type: 'org', orgId: 'org-1' }) + expect(renderHook(() => useCurrentScope({})).result.current).toEqual({ type: 'global' }) + }) +}) + +describe('matchesCurrentScope', () => { + const projectTask = createProjectMetadata(project, org) + const orgTask = createOrgMetadata(org) + const userTask = createUserMetadata() + + it('matches a project task only in that project', () => { + expect(matchesCurrentScope(projectTask, { type: 'project', projectId: 'proj-1' })).toBe(true) + expect(matchesCurrentScope(projectTask, { type: 'project', projectId: 'proj-2' })).toBe(false) + }) + + it('matches an org task in that org, but not the org\'s project tasks', () => { + expect(matchesCurrentScope(orgTask, { type: 'org', orgId: 'org-1' })).toBe(true) + expect(matchesCurrentScope(projectTask, { type: 'org', orgId: 'org-1' })).toBe(false) + }) + + it('matches nothing on a global page or without metadata', () => { + expect(matchesCurrentScope(userTask, { type: 'global' })).toBe(false) + expect(matchesCurrentScope(undefined, { type: 'project', projectId: 'proj-1' })).toBe(false) + }) +}) + +describe('getContextLabel', () => { + it('labels each scope', () => { + expect(getContextLabel(createProjectMetadata(project, org))).toBe('Project: Web') + expect(getContextLabel(createOrgMetadata(org))).toBe('Org: Acme') + expect(getContextLabel(createUserMetadata())).toBe('User') + expect(getContextLabel({ scope: 'edge', projectName: 'Web' })).toBe('AI Edge: Web') + expect(getContextLabel({ scope: 'billing' })).toBe('Billing') + expect(getContextLabel(undefined)).toBeUndefined() + }) +}) + +describe('useTasksWithLabels', () => { + const task = (metadata: Task['metadata']) => ({ id: String(Math.random()), metadata }) as Task + + it('shows no labels without tasks or when every task belongs to the current project', () => { + expect(renderHook(() => useTasksWithLabels([], { projectId: 'proj-1' })).result.current.showLabels).toBe(false) + const tasks = [task(createProjectMetadata(project, org))] + expect(renderHook(() => useTasksWithLabels(tasks, { projectId: 'proj-1' })).result.current.showLabels).toBe(false) + }) + + it('shows labels on a global page and for mixed scopes', () => { + const tasks = [task(createProjectMetadata(project, org)), task(createOrgMetadata(org))] + expect(renderHook(() => useTasksWithLabels(tasks, {})).result.current.showLabels).toBe(true) + expect(renderHook(() => useTasksWithLabels(tasks, { projectId: 'proj-1' })).result.current.showLabels).toBe(true) + }) +}) From 2fe7d290e50d17d8e7aecabb08c517799feda745 Mon Sep 17 00:00:00 2001 From: Yahya Fakhroji Date: Thu, 19 Nov 2026 14:51:42 +0700 Subject: [PATCH 6/7] test(place-autocomplete): wait for a fresh error message Typing starts a search per letter, so the error-state test could hold an element an earlier search rendered just before the component replaced it, and failed now and then in the full run. It now waits for a fresh match. --- .../place-autocomplete/__tests__/place-autocomplete.test.tsx | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/packages/datum-ui/src/components/base/place-autocomplete/__tests__/place-autocomplete.test.tsx b/packages/datum-ui/src/components/base/place-autocomplete/__tests__/place-autocomplete.test.tsx index 1b4d7b75..7fad9f6a 100644 --- a/packages/datum-ui/src/components/base/place-autocomplete/__tests__/place-autocomplete.test.tsx +++ b/packages/datum-ui/src/components/base/place-autocomplete/__tests__/place-autocomplete.test.tsx @@ -75,7 +75,9 @@ describe('placeAutocomplete', () => { vi.stubGlobal('fetch', vi.fn().mockRejectedValue(new Error('network down'))) render() await userEvent.type(screen.getByPlaceholderText('Search'), 'Berlin') - expect(await screen.findByText(/network down/)).toBeInTheDocument() + // Each letter starts a search, so query afresh rather than hold an element an + // earlier search rendered. + await waitFor(() => expect(screen.getByText(/network down/)).toBeInTheDocument()) }) it('cancels an earlier search so its late response never replaces the latest results', async () => { From 74ccf15ff7988a942713b23f98ffdad6571584ad Mon Sep 17 00:00:00 2001 From: Yahya Fakhroji Date: Thu, 19 Nov 2026 14:59:40 +0700 Subject: [PATCH 7/7] test: make three tests fail when their behaviour breaks The bare-b sidebar test pressed b twice, so with the Cmd/Ctrl check removed the two toggles cancelled out and it still passed. The task status-filter test had one task, so it passed without the filter. The search test read the last request URL before the final keystroke's search could run. Each now fails with its behaviour removed: separate bare-b tests, a never-finishing task beside the completed one, and a wait for the full query. --- .../__tests__/place-autocomplete.test.tsx | 3 ++- .../src/components/base/sidebar/__tests__/sidebar.test.tsx | 7 ++++++- .../features/task-queue/hooks/__tests__/hooks.test.tsx | 3 +++ 3 files changed, 11 insertions(+), 2 deletions(-) diff --git a/packages/datum-ui/src/components/base/place-autocomplete/__tests__/place-autocomplete.test.tsx b/packages/datum-ui/src/components/base/place-autocomplete/__tests__/place-autocomplete.test.tsx index 7fad9f6a..921ec5e5 100644 --- a/packages/datum-ui/src/components/base/place-autocomplete/__tests__/place-autocomplete.test.tsx +++ b/packages/datum-ui/src/components/base/place-autocomplete/__tests__/place-autocomplete.test.tsx @@ -27,7 +27,8 @@ describe('placeAutocomplete', () => { await userEvent.type(screen.getByPlaceholderText('Search'), 'Berlin') expect(await screen.findByRole('option', { name: /Berlin/ })).toBeInTheDocument() expect(screen.getByRole('option', { name: /Bern/ })).toBeInTheDocument() - expect(String(fetchFn.mock.calls.at(-1)?.[0])).toContain('Berlin') + // The list can show an earlier keystroke's results first; wait for the full query. + await waitFor(() => expect(String(fetchFn.mock.calls.at(-1)?.[0])).toContain('Berlin')) await waitFor(() => expect(onResultsChange).toHaveBeenLastCalledWith(expect.arrayContaining([expect.objectContaining({ properties: expect.objectContaining({ name: 'Berlin' }) })]))) }) diff --git a/packages/datum-ui/src/components/base/sidebar/__tests__/sidebar.test.tsx b/packages/datum-ui/src/components/base/sidebar/__tests__/sidebar.test.tsx index 2d1fb58f..b58a13ae 100644 --- a/packages/datum-ui/src/components/base/sidebar/__tests__/sidebar.test.tsx +++ b/packages/datum-ui/src/components/base/sidebar/__tests__/sidebar.test.tsx @@ -65,9 +65,14 @@ describe('sidebarProvider', () => { expect(state()).toBe('expanded') }) - it('ignores a bare b, including one typed in the sidebar input', async () => { + it('ignores a bare b pressed on the page', () => { renderSidebar() fireEvent.keyDown(window, { key: 'b' }) + expect(state()).toBe('expanded') + }) + + it('ignores a b typed in the sidebar input', async () => { + renderSidebar() await userEvent.type(screen.getByPlaceholderText('Filter'), 'b') expect(state()).toBe('expanded') }) diff --git a/packages/datum-ui/src/components/features/task-queue/hooks/__tests__/hooks.test.tsx b/packages/datum-ui/src/components/features/task-queue/hooks/__tests__/hooks.test.tsx index 74ca0343..7587fbc6 100644 --- a/packages/datum-ui/src/components/features/task-queue/hooks/__tests__/hooks.test.tsx +++ b/packages/datum-ui/src/components/features/task-queue/hooks/__tests__/hooks.test.tsx @@ -47,9 +47,12 @@ describe('useTaskQueue', () => { const { result } = renderHook(() => useTaskQueue({ status: 'completed' }), { wrapper }) let id = '' act(() => { + // A task that never finishes must stay out of the completed list. + result.current.enqueue({ title: 'Never done', processor: () => new Promise(() => {}) }) id = result.current.enqueue({ title: 'Quick task', processor: async () => {} }).id }) await waitFor(() => expect(result.current.tasks.map(task => task.id)).toEqual([id])) + expect(result.current.tasks.every(task => task.status === 'completed')).toBe(true) act(() => result.current.dismiss(id)) await waitFor(() => expect(result.current.tasks).toHaveLength(0)) })