feat(admin-ui): RequireAuth gate + RTL component тесты
RequireAuth: гейтит весь UI по аутентификации. Anonymous юзер вместо красного "AxiosError 401" получает immediate signinRedirect на Keycloak; authenticated юзер с истёкшим токеном получает silent renew → fallback на full redirect. Guards против infinite loop: - auth.isLoading / activeNavigator — bootstrap или signin/signout уже идёт - ?error= в URL — вернулись с провалом из Keycloak, показываем сообщение - auth.error без isAuthenticated — Keycloak недоступен, показываем сообщение main.tsx: RequireAuth обёрнут вокруг Router/Query, чтобы tan-stack-router и React Query не делали запросов до auth (иначе 401-каскад на старте). TokenSync: 401 interceptor теперь редиректит и anonymous (раньше срабатывал только для authenticated с истёкшим токеном), с теми же guards. RTL component тесты — 22 теста на 3 ключевых компонента: - SchemaBuilder (7): empty state, add/remove/reorder properties - PropertyEditor (10): kind change, required/unique toggle, kind-specific поля (string→pattern, integer→min/max, enum→values, array_string→uniqueItems), move up/down disabled на boundaries - SchemaDrivenForm (5): identity tab с required, переключение на extra, isPending → save disabled, cancel callback, serverError → Alert Setup: - vite.config.ts: test block (jsdom env, setup file, css off) - src/test/setup.ts: jest-dom matchers, cleanup, HTMLCanvasElement.getContext stub (lottie-web из @nstart/ui крашит в jsdom без canvas) - src/test/render.tsx: renderWithI18n helper, форсит ru-RU (LanguageDetector в node по умолчанию даёт en-US) Deps: +@testing-library/react +@testing-library/jest-dom +@testing-library/user-event +jsdom
This commit is contained in:
@@ -0,0 +1,110 @@
|
||||
import { describe, it, expect, vi } from 'vitest'
|
||||
import { screen } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { renderWithI18n } from '@/test/render'
|
||||
import { SchemaDrivenForm } from './SchemaDrivenForm'
|
||||
import type { JsonSchema } from '@/api/client'
|
||||
|
||||
const minimalSchema: JsonSchema = {
|
||||
$schema: 'http://json-schema.org/draft-07/schema#',
|
||||
type: 'object',
|
||||
additionalProperties: false,
|
||||
required: ['code', 'name'],
|
||||
'x-id-source': 'code',
|
||||
properties: {
|
||||
code: { type: 'string', minLength: 1, 'x-unique': true },
|
||||
name: { type: 'string', minLength: 1 },
|
||||
description: { type: 'string' },
|
||||
},
|
||||
} as JsonSchema
|
||||
|
||||
describe('SchemaDrivenForm', () => {
|
||||
it('рендерит идентификационный таб с required-полями', () => {
|
||||
renderWithI18n(
|
||||
<SchemaDrivenForm
|
||||
schema={minimalSchema}
|
||||
supportedLocales={['ru-RU', 'en-US']}
|
||||
defaultLocale="ru-RU"
|
||||
mode="create"
|
||||
isPending={false}
|
||||
onSubmit={() => {}}
|
||||
onCancel={() => {}}
|
||||
/>,
|
||||
)
|
||||
// x-id-source: 'code' → бизнес-ключ автогенерится, показывается hint
|
||||
expect(screen.getByText(/Бизнес-ключ создастся автоматически/)).toBeInTheDocument()
|
||||
// Required-поля code/name на табе "Идентификация". i18n field.code=Код,
|
||||
// field.name=Наименование (см. src/i18n.ts).
|
||||
expect(screen.getByText('Код')).toBeInTheDocument()
|
||||
expect(screen.getByText('Наименование')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('переключение на таб "Дополнительно" показывает optional поля', async () => {
|
||||
const user = userEvent.setup()
|
||||
renderWithI18n(
|
||||
<SchemaDrivenForm
|
||||
schema={minimalSchema}
|
||||
supportedLocales={['ru-RU']}
|
||||
defaultLocale="ru-RU"
|
||||
mode="create"
|
||||
isPending={false}
|
||||
onSubmit={() => {}}
|
||||
onCancel={() => {}}
|
||||
/>,
|
||||
)
|
||||
// @nstart/ui Tabs использует role="button" не "tab".
|
||||
await user.click(screen.getByRole('button', { name: /Дополнительно/i }))
|
||||
// description (optional) теперь виден. i18n field.description=Описание.
|
||||
expect(screen.getByText('Описание')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('disabled Save кнопка пока isPending', () => {
|
||||
renderWithI18n(
|
||||
<SchemaDrivenForm
|
||||
schema={minimalSchema}
|
||||
supportedLocales={['ru-RU']}
|
||||
defaultLocale="ru-RU"
|
||||
mode="create"
|
||||
isPending={true}
|
||||
onSubmit={() => {}}
|
||||
onCancel={() => {}}
|
||||
/>,
|
||||
)
|
||||
const saveBtn = screen.getByRole('button', { name: /Сохранение/i })
|
||||
expect(saveBtn).toBeDisabled()
|
||||
})
|
||||
|
||||
it('Cancel вызывает onCancel', async () => {
|
||||
const user = userEvent.setup()
|
||||
const onCancel = vi.fn()
|
||||
renderWithI18n(
|
||||
<SchemaDrivenForm
|
||||
schema={minimalSchema}
|
||||
supportedLocales={['ru-RU']}
|
||||
defaultLocale="ru-RU"
|
||||
mode="create"
|
||||
isPending={false}
|
||||
onSubmit={() => {}}
|
||||
onCancel={onCancel}
|
||||
/>,
|
||||
)
|
||||
await user.click(screen.getByRole('button', { name: 'Отмена' }))
|
||||
expect(onCancel).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('serverError рендерится как Alert', () => {
|
||||
renderWithI18n(
|
||||
<SchemaDrivenForm
|
||||
schema={minimalSchema}
|
||||
supportedLocales={['ru-RU']}
|
||||
defaultLocale="ru-RU"
|
||||
mode="create"
|
||||
isPending={false}
|
||||
serverError="Дубликат business_key"
|
||||
onSubmit={() => {}}
|
||||
onCancel={() => {}}
|
||||
/>,
|
||||
)
|
||||
expect(screen.getByText('Дубликат business_key')).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
Reference in New Issue
Block a user