test(10-05): bring every SPA module, composable and component under Vitest

- 41 unit and component suites under admin/tests/{app,state,shell,list,form,relation,views,ui}
  covering states and a11y roles; every src module is imported by a test
- typed fixture helper assigns each JSON fixture to its generated OpenAPI type
- fix: iconFor ignores inherited object members such as "constructor"
- fix: field controls import ./control instead of the registry (import cycle
  left a renderer unregistered depending on module load order)
- fix: dropdown shows the placeholder for an unknown stored value next to an emptyOption
- fix: list announces a failed schema load even when the rows arrive after it
- tailwind no longer scans admin/tests; boardwalk/dist rebuilt
This commit is contained in:
Jakub Zych
2026-09-27 17:53:57 +02:00
parent 8259a456bb
commit 1c2a66df45
61 changed files with 4299 additions and 91 deletions

View File

@@ -0,0 +1,141 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { clearUser, currentUser, login, logout, me, useAuth } from '../../src/state/useAuth'
import { navigation, setNavigation } from '../../src/state/useNavigation'
import { setSettings, settings } from '../../src/state/useSettings'
import { navigationFixture, settingsFixture } from '../fixtures/typed'
import { API, mockApi, profile, requestsTo, resetState } from '../helpers'
const loginOk = (expiresIn: unknown) => ({ body: { data: { token_type: 'cookie', expires_in: expiresIn }, meta: {} } })
const refreshOk = { body: { data: { token_type: 'cookie', expires_in: 50 }, meta: {} } }
const unauthorized = { status: 401, body: { error: { code: 'unauthenticated', message: 'no', details: {} } } }
beforeEach(() => {
resetState()
})
afterEach(() => {
clearUser()
vi.useRealTimers()
})
describe('login', () => {
it('posts the credentials and schedules the proactive refresh at 80 percent', async () => {
vi.useFakeTimers()
const calls = mockApi({ [`POST ${API}/auth/login`]: loginOk(100), [`POST ${API}/auth/refresh`]: refreshOk })
expect(await login('dev', 'secret')).toBe(true)
const body = (await requestsTo(calls, 'POST', `${API}/auth/login`)[0]!.clone().json()) as Record<string, string>
expect(body).toEqual({ login: 'dev', password: 'secret' })
expect(useAuth().expiresIn.value).toBe(100)
await vi.advanceTimersByTimeAsync(79_999)
expect(requestsTo(calls, 'POST', `${API}/auth/refresh`)).toHaveLength(0)
await vi.advanceTimersByTimeAsync(1)
expect(requestsTo(calls, 'POST', `${API}/auth/refresh`)).toHaveLength(1)
// The refresh reschedules from its own lifetime (50 s -> 40 s).
expect(useAuth().expiresIn.value).toBe(50)
await vi.advanceTimersByTimeAsync(40_000)
expect(requestsTo(calls, 'POST', `${API}/auth/refresh`)).toHaveLength(2)
})
it('answers false on rejected credentials and schedules nothing', async () => {
vi.useFakeTimers()
const calls = mockApi({ [`POST ${API}/auth/login`]: unauthorized, [`POST ${API}/auth/refresh`]: refreshOk })
expect(await login('dev', 'bad')).toBe(false)
await vi.advanceTimersByTimeAsync(10_000_000)
expect(requestsTo(calls, 'POST', `${API}/auth/refresh`)).toHaveLength(0)
})
it.each([0, -5, 'soon', null])('schedules no refresh for the lifetime %j', async (expiresIn) => {
vi.useFakeTimers()
const calls = mockApi({ [`POST ${API}/auth/login`]: loginOk(expiresIn), [`POST ${API}/auth/refresh`]: refreshOk })
expect(await login('dev', 'secret')).toBe(true)
await vi.advanceTimersByTimeAsync(10_000_000)
expect(requestsTo(calls, 'POST', `${API}/auth/refresh`)).toHaveLength(0)
})
})
describe('me and clearUser', () => {
it('loads the profile, and clears it on 401', async () => {
mockApi({ [`GET ${API}/auth/me`]: { body: profile } })
expect((await me())?.login).toBe('dev')
expect(currentUser.value?.role?.name).toBe('Developer')
mockApi({ [`GET ${API}/auth/me`]: unauthorized })
expect(await me()).toBeNull()
expect(currentUser.value).toBeNull()
})
it('clearUser forgets the user and cancels the pending refresh', async () => {
vi.useFakeTimers()
const calls = mockApi({
[`GET ${API}/auth/me`]: { body: profile },
[`POST ${API}/auth/login`]: loginOk(10),
[`POST ${API}/auth/refresh`]: refreshOk,
})
await login('dev', 'secret')
await me()
clearUser()
expect(currentUser.value).toBeNull()
expect(useAuth().expiresIn.value).toBeNull()
await vi.advanceTimersByTimeAsync(60_000)
expect(requestsTo(calls, 'POST', `${API}/auth/refresh`)).toHaveLength(0)
})
})
describe('logout (T-10-23)', () => {
async function signedIn(logoutRoute: Parameters<typeof mockApi>[0][string] | 'throw') {
const routes: Parameters<typeof mockApi>[0] = { [`GET ${API}/auth/me`]: { body: profile } }
if (logoutRoute !== 'throw') {
routes[`POST ${API}/auth/logout`] = logoutRoute
}
const calls = mockApi(routes)
await me()
setNavigation(navigationFixture.data)
setSettings(settingsFixture.list.data)
if (logoutRoute === 'throw') {
vi.spyOn(globalThis, 'fetch').mockRejectedValue(new TypeError('offline'))
}
return calls
}
it.each([
['succeeds', { body: { data: { status: 'logged_out' }, meta: {} } }],
['answers 500', { status: 500, body: { error: { code: 'server', message: 'x', details: {} } } }],
['fails on the network', 'throw' as const],
])('clears the user, navigation and settings and routes to login when the call %s', async (_label, route) => {
const calls = await signedIn(route)
const router = { replace: vi.fn().mockResolvedValue(undefined) }
await logout(router)
expect(currentUser.value).toBeNull()
expect(navigation.value).toEqual([])
expect(settings.value).toEqual([])
expect(router.replace).toHaveBeenCalledWith({ name: 'login' })
if (route !== 'throw') {
const posted = requestsTo(calls, 'POST', `${API}/auth/logout`)
expect(posted).toHaveLength(1)
expect(posted[0]!.headers.get('X-Requested-With')).toBe('XMLHttpRequest')
}
})
it('works without a router and swallows a failed navigation', async () => {
await signedIn({ body: { data: { status: 'logged_out' }, meta: {} } })
await expect(logout()).resolves.toBeUndefined()
expect(currentUser.value).toBeNull()
await signedIn({ body: { data: { status: 'logged_out' }, meta: {} } })
await expect(logout({ replace: vi.fn().mockRejectedValue(new Error('aborted')) })).resolves.toBeUndefined()
expect(currentUser.value).toBeNull()
})
it('exposes the session API through useAuth', () => {
const auth = useAuth()
expect(auth.user).toBe(currentUser)
expect(auth.login).toBe(login)
expect(auth.logout).toBe(logout)
expect(auth.me).toBe(me)
expect(auth.clearUser).toBe(clearUser)
})
})

View File

@@ -0,0 +1,12 @@
import { describe, expect, it } from 'vitest'
import { clearRecordCrumb, recordCrumb, setRecordCrumb } from '../../src/state/useBreadcrumbs'
describe('record crumb', () => {
it('publishes and clears the record title', () => {
expect(recordCrumb.value).toBe('')
setRecordCrumb('Blue widget')
expect(recordCrumb.value).toBe('Blue widget')
clearRecordCrumb()
expect(recordCrumb.value).toBe('')
})
})

View File

@@ -0,0 +1,80 @@
import { beforeEach, describe, expect, it } from 'vitest'
import type { NavigationEntry } from '../../src/api/types'
import {
activeEntry,
firstControllerPath,
homePath,
loadNavigation,
navigation,
railEntries,
setNavigation,
useNavigation,
} from '../../src/state/useNavigation'
import { clone, navigationFixture } from '../fixtures/typed'
import { API, mockApi, requestsTo, resetState } from '../helpers'
function entry(code: string, order: number, controllers: string[], controller = controllers[0] ?? 'x.y.z'): NavigationEntry {
return {
code,
label: code,
icon: 'tags',
order,
controller,
sideMenu: controllers.map((id, index) => ({ code: `${code}-${index}`, label: id, icon: 'tags', order: 0, controller: id, sideMenu: [] })),
}
}
beforeEach(() => {
resetState()
})
describe('loadNavigation', () => {
it('stores the server-filtered entries', async () => {
const calls = mockApi({ [`GET ${API}/navigation`]: { body: navigationFixture } })
expect(await loadNavigation()).toHaveLength(3)
expect(navigation.value.map((item) => item.code)).toEqual(['demo', 'tools', 'hidden'])
expect(requestsTo(calls, 'GET', `${API}/navigation`)).toHaveLength(1)
})
it('empties the navigation when the request fails', async () => {
setNavigation(navigationFixture.data)
mockApi({ [`GET ${API}/navigation`]: { status: 403, body: { error: { code: 'forbidden', message: 'x', details: {} } } } })
expect(await loadNavigation()).toEqual([])
expect(navigation.value).toEqual([])
})
})
describe('rail entries', () => {
it('omits plugins without a permitted side-menu item and orders by order, then position', () => {
setNavigation([entry('b', 20, ['a.b.c']), entry('empty', 1, []), entry('a', 10, ['a.a.c']), entry('c', 20, ['a.c.c'])])
expect(railEntries.value.map((item) => item.code)).toEqual(['a', 'b', 'c'])
})
it('opens the first valid side-menu controller, else the entry controller', () => {
expect(firstControllerPath(entry('p', 0, ['bad id', 'acme.demo.gadgets']))).toBe('/acme/demo/gadgets')
expect(firstControllerPath({ ...entry('p', 0, ['bad id']), controller: 'acme.demo.widgets' })).toBe('/acme/demo/widgets')
expect(firstControllerPath({ ...entry('p', 0, []), controller: 'nope' })).toBeNull()
})
it('finds the active plugin by its own controller or any side-menu controller', () => {
setNavigation(navigationFixture.data)
expect(activeEntry('acme', 'demo')?.code).toBe('demo')
expect(activeEntry('acme', 'tools')?.code).toBe('tools')
expect(activeEntry('acme', 'hidden')).toBeNull()
expect(activeEntry('acme', 'missing')).toBeNull()
const shared = clone(navigationFixture.data)
shared[0]!.controller = 'other.root.index'
setNavigation(shared)
expect(activeEntry('acme', 'demo')?.code).toBe('demo')
})
it('goes home to the first rail plugin, skipping plugins without a valid path', () => {
expect(homePath()).toBeNull()
setNavigation([{ ...entry('broken', 1, ['bad id']), controller: 'bad' }, entry('ok', 2, ['acme.tools.hammers'])])
expect(homePath()).toBe('/acme/tools/hammers')
setNavigation(navigationFixture.data)
expect(homePath()).toBe('/acme/demo/widgets')
expect(useNavigation().homePath).toBe(homePath)
})
})

View File

@@ -0,0 +1,47 @@
import { beforeEach, describe, expect, it } from 'vitest'
import {
hasSettings,
loadSettings,
setSettings,
settings,
settingsEntry,
settingsGroups,
useSettings,
} from '../../src/state/useSettings'
import { settingsFixture } from '../fixtures/typed'
import { API, mockApi, resetState } from '../helpers'
beforeEach(() => {
resetState()
})
describe('useSettings (D-21)', () => {
it('is hidden until at least one settings page is permitted', async () => {
expect(hasSettings.value).toBe(false)
mockApi({ [`GET ${API}/settings`]: { body: settingsFixture.list } })
expect(await loadSettings()).toHaveLength(3)
expect(hasSettings.value).toBe(true)
expect(useSettings().settings).toBe(settings)
})
it('hides settings again when the request fails', async () => {
setSettings(settingsFixture.list.data)
mockApi({ [`GET ${API}/settings`]: { status: 403, body: { error: { code: 'forbidden', message: 'x', details: {} } } } })
expect(await loadSettings()).toEqual([])
expect(hasSettings.value).toBe(false)
})
it('finds an entry by code', () => {
setSettings(settingsFixture.list.data)
expect(settingsEntry('mail')?.label).toBe('Mail')
expect(settingsEntry('nope')).toBeNull()
})
it('groups by category in first-seen order after sorting by order', () => {
setSettings(settingsFixture.list.data)
expect(settingsGroups.value.map((group) => [group.category, group.entries.map((entry) => entry.code)])).toEqual([
['Appearance', ['branding']],
['System', ['mail', 'search']],
])
})
})

View File

@@ -0,0 +1,95 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { NARROW_QUERY, SIDEBAR_KEY, setCollapsed, sidebarCollapsed, useSidebar, watchViewport } from '../../src/state/useSidebar'
import { fakeMedia, resetState } from '../helpers'
let stop: (() => void) | null = null
beforeEach(() => {
resetState()
stop = null
})
afterEach(() => {
stop?.()
setCollapsed(false)
window.localStorage.clear()
})
describe('useSidebar (D-06, T-10-22)', () => {
it('uses the documented storage key and breakpoint', () => {
expect(SIDEBAR_KEY).toBe('summer-admin.sidebar')
expect(NARROW_QUERY).toBe('(max-width: 1099px)')
})
it('restores the persisted manual choice on a wide viewport', () => {
fakeMedia({ [NARROW_QUERY]: false })
window.localStorage.setItem(SIDEBAR_KEY, 'true')
stop = watchViewport()
expect(sidebarCollapsed.value).toBe(true)
expect(useSidebar().manual.value).toBe(true)
expect(useSidebar().narrow.value).toBe(false)
window.localStorage.setItem(SIDEBAR_KEY, 'yes')
stop()
stop = watchViewport()
expect(sidebarCollapsed.value).toBe(false)
})
it('collapses below the breakpoint without writing the stored choice', () => {
const media = fakeMedia({ [NARROW_QUERY]: true })
stop = watchViewport()
expect(sidebarCollapsed.value).toBe(true)
expect(useSidebar().narrow.value).toBe(true)
expect(window.localStorage.getItem(SIDEBAR_KEY)).toBeNull()
media.change(NARROW_QUERY, false)
expect(sidebarCollapsed.value).toBe(false)
expect(window.localStorage.getItem(SIDEBAR_KEY)).toBeNull()
stop()
stop = null
expect(media.listeners(NARROW_QUERY)).toBe(0)
media.change(NARROW_QUERY, true)
expect(useSidebar().narrow.value).toBe(false)
})
it("stores only 'true' or 'false' and nothing else", () => {
fakeMedia({})
stop = watchViewport()
setCollapsed(true)
expect(window.localStorage.getItem(SIDEBAR_KEY)).toBe('true')
expect(sidebarCollapsed.value).toBe(true)
setCollapsed(false)
expect(window.localStorage.getItem(SIDEBAR_KEY)).toBe('false')
expect(sidebarCollapsed.value).toBe(false)
expect(Object.keys(window.localStorage)).toEqual([SIDEBAR_KEY])
})
it('keeps the choice for the session when storage is unavailable', () => {
fakeMedia({})
vi.spyOn(Storage.prototype, 'setItem').mockImplementation(() => {
throw new DOMException('full', 'QuotaExceededError')
})
vi.spyOn(Storage.prototype, 'getItem').mockImplementation(() => {
throw new DOMException('denied', 'SecurityError')
})
stop = watchViewport()
expect(sidebarCollapsed.value).toBe(false)
setCollapsed(true)
expect(sidebarCollapsed.value).toBe(true)
})
it('never collapses by viewport when matchMedia is missing', () => {
const original = window.matchMedia
// @ts-expect-error simulating a browser without matchMedia
window.matchMedia = undefined
try {
stop = watchViewport()
expect(useSidebar().narrow.value).toBe(false)
expect(stop()).toBeUndefined()
stop = null
} finally {
window.matchMedia = original
}
})
})

View File

@@ -0,0 +1,54 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { clearToasts, dismissToast, showToast, TOAST_TIMEOUT, toasts, useToasts } from '../../src/state/useToasts'
beforeEach(() => {
vi.useFakeTimers()
clearToasts()
})
afterEach(() => {
clearToasts()
vi.useRealTimers()
})
describe('toast queue', () => {
it('queues newest first with success as the default tone', () => {
const first = showToast('Saved')
const second = showToast('Failed', 'danger')
expect(second).toBeGreaterThan(first)
expect(toasts.value.map((item) => [item.text, item.tone])).toEqual([
['Failed', 'danger'],
['Saved', 'success'],
])
})
it('dismisses each toast after about 4 seconds', () => {
expect(TOAST_TIMEOUT).toBe(4000)
showToast('one')
vi.advanceTimersByTime(1000)
showToast('two')
vi.advanceTimersByTime(TOAST_TIMEOUT - 1000)
expect(toasts.value.map((item) => item.text)).toEqual(['two'])
vi.advanceTimersByTime(1000)
expect(toasts.value).toEqual([])
})
it('dismisses on request and cancels that toast timer', () => {
const id = showToast('bye')
const other = showToast('stay')
dismissToast(id)
expect(toasts.value.map((item) => item.id)).toEqual([other])
dismissToast(id)
dismissToast(999_999)
expect(vi.getTimerCount()).toBe(1)
})
it('clears every toast and timer', () => {
showToast('a')
showToast('b')
clearToasts()
expect(toasts.value).toEqual([])
expect(vi.getTimerCount()).toBe(0)
expect(useToasts().showToast).toBe(showToast)
})
})