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()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,194 @@
|
||||
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 { PropertyEditor } from './PropertyEditor'
|
||||
import type { PropertyDef } from './types'
|
||||
|
||||
const baseProp = (overrides: Partial<PropertyDef> = {}): PropertyDef => ({
|
||||
id: 'prop-1',
|
||||
name: 'designator',
|
||||
kind: 'string',
|
||||
required: false,
|
||||
unique: false,
|
||||
...overrides,
|
||||
})
|
||||
|
||||
describe('PropertyEditor', () => {
|
||||
it('меняет name при вводе → onChange с обновлённым name', async () => {
|
||||
const user = userEvent.setup()
|
||||
const onChange = vi.fn()
|
||||
renderWithI18n(
|
||||
<PropertyEditor
|
||||
prop={baseProp({ name: '' })}
|
||||
index={0}
|
||||
total={1}
|
||||
onChange={onChange}
|
||||
onRemove={() => {}}
|
||||
onMoveUp={() => {}}
|
||||
onMoveDown={() => {}}
|
||||
/>,
|
||||
)
|
||||
// @nstart/ui TextInput не биндит label через for/id — ищем по placeholder.
|
||||
const nameInput = screen.getByPlaceholderText('snake_case_key') as HTMLInputElement
|
||||
await user.type(nameInput, 'n')
|
||||
// Controlled — value не обновляется без re-render с новым prop, поэтому
|
||||
// достаточно проверить что onChange выстрелил с ожидаемым name.
|
||||
expect(onChange).toHaveBeenCalledWith(expect.objectContaining({ name: 'n' }))
|
||||
})
|
||||
|
||||
it('toggle required чекбокса → onChange c required:true', async () => {
|
||||
const user = userEvent.setup()
|
||||
const onChange = vi.fn()
|
||||
renderWithI18n(
|
||||
<PropertyEditor
|
||||
prop={baseProp({ required: false })}
|
||||
index={0}
|
||||
total={1}
|
||||
onChange={onChange}
|
||||
onRemove={() => {}}
|
||||
onMoveUp={() => {}}
|
||||
onMoveDown={() => {}}
|
||||
/>,
|
||||
)
|
||||
await user.click(screen.getByLabelText('Обязательное'))
|
||||
expect(onChange).toHaveBeenCalledWith(expect.objectContaining({ required: true }))
|
||||
})
|
||||
|
||||
it('toggle unique → onChange c unique:true', async () => {
|
||||
const user = userEvent.setup()
|
||||
const onChange = vi.fn()
|
||||
renderWithI18n(
|
||||
<PropertyEditor
|
||||
prop={baseProp({ unique: false })}
|
||||
index={0}
|
||||
total={1}
|
||||
onChange={onChange}
|
||||
onRemove={() => {}}
|
||||
onMoveUp={() => {}}
|
||||
onMoveDown={() => {}}
|
||||
/>,
|
||||
)
|
||||
// У Checkbox label включает description "Дубликаты по этому полю запрещены"
|
||||
// — getByLabelText использует match на полный текст label элемента.
|
||||
await user.click(screen.getByLabelText(/Уникальное/))
|
||||
expect(onChange).toHaveBeenCalledWith(expect.objectContaining({ unique: true }))
|
||||
})
|
||||
|
||||
it('для kind=string показывает minLength/maxLength/pattern', () => {
|
||||
renderWithI18n(
|
||||
<PropertyEditor
|
||||
prop={baseProp({ kind: 'string' })}
|
||||
index={0}
|
||||
total={1}
|
||||
onChange={() => {}}
|
||||
onRemove={() => {}}
|
||||
onMoveUp={() => {}}
|
||||
onMoveDown={() => {}}
|
||||
/>,
|
||||
)
|
||||
// @nstart/ui TextInput не биндит label через for/id — проверяем по
|
||||
// visible-тексту labels.
|
||||
expect(screen.getByText('minLength')).toBeInTheDocument()
|
||||
expect(screen.getByText('maxLength')).toBeInTheDocument()
|
||||
expect(screen.getByText('Pattern (regex)')).toBeInTheDocument()
|
||||
// Pattern имеет уникальный placeholder — проверяем что input реально есть.
|
||||
expect(screen.getByPlaceholderText('^[A-Z]{2}$')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('для kind=integer показывает minimum/maximum (не string-поля)', () => {
|
||||
renderWithI18n(
|
||||
<PropertyEditor
|
||||
prop={baseProp({ kind: 'integer' })}
|
||||
index={0}
|
||||
total={1}
|
||||
onChange={() => {}}
|
||||
onRemove={() => {}}
|
||||
onMoveUp={() => {}}
|
||||
onMoveDown={() => {}}
|
||||
/>,
|
||||
)
|
||||
expect(screen.getByText('minimum')).toBeInTheDocument()
|
||||
expect(screen.getByText('maximum')).toBeInTheDocument()
|
||||
expect(screen.queryByText('Pattern (regex)')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('для kind=enum показывает enum values input с pre-filled значением', () => {
|
||||
renderWithI18n(
|
||||
<PropertyEditor
|
||||
prop={baseProp({ kind: 'enum', enumValues: ['A', 'B'] })}
|
||||
index={0}
|
||||
total={1}
|
||||
onChange={() => {}}
|
||||
onRemove={() => {}}
|
||||
onMoveUp={() => {}}
|
||||
onMoveDown={() => {}}
|
||||
/>,
|
||||
)
|
||||
expect(screen.getByText('Значения enum (через запятую)')).toBeInTheDocument()
|
||||
expect(screen.getByDisplayValue('A, B')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('для kind=array_string появляется uniqueItems checkbox', () => {
|
||||
renderWithI18n(
|
||||
<PropertyEditor
|
||||
prop={baseProp({ kind: 'array_string' })}
|
||||
index={0}
|
||||
total={1}
|
||||
onChange={() => {}}
|
||||
onRemove={() => {}}
|
||||
onMoveUp={() => {}}
|
||||
onMoveDown={() => {}}
|
||||
/>,
|
||||
)
|
||||
expect(screen.getByLabelText('uniqueItems')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('moveUp disabled когда index=0', () => {
|
||||
renderWithI18n(
|
||||
<PropertyEditor
|
||||
prop={baseProp()}
|
||||
index={0}
|
||||
total={3}
|
||||
onChange={() => {}}
|
||||
onRemove={() => {}}
|
||||
onMoveUp={() => {}}
|
||||
onMoveDown={() => {}}
|
||||
/>,
|
||||
)
|
||||
expect(screen.getByRole('button', { name: 'Выше' })).toBeDisabled()
|
||||
})
|
||||
|
||||
it('moveDown disabled когда index=total-1', () => {
|
||||
renderWithI18n(
|
||||
<PropertyEditor
|
||||
prop={baseProp()}
|
||||
index={2}
|
||||
total={3}
|
||||
onChange={() => {}}
|
||||
onRemove={() => {}}
|
||||
onMoveUp={() => {}}
|
||||
onMoveDown={() => {}}
|
||||
/>,
|
||||
)
|
||||
expect(screen.getByRole('button', { name: 'Ниже' })).toBeDisabled()
|
||||
})
|
||||
|
||||
it('клик Удалить → onRemove', async () => {
|
||||
const user = userEvent.setup()
|
||||
const onRemove = vi.fn()
|
||||
renderWithI18n(
|
||||
<PropertyEditor
|
||||
prop={baseProp()}
|
||||
index={1}
|
||||
total={3}
|
||||
onChange={() => {}}
|
||||
onRemove={onRemove}
|
||||
onMoveUp={() => {}}
|
||||
onMoveDown={() => {}}
|
||||
/>,
|
||||
)
|
||||
await user.click(screen.getByRole('button', { name: 'Удалить' }))
|
||||
expect(onRemove).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,95 @@
|
||||
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 { SchemaBuilder } from './SchemaBuilder'
|
||||
import type { PropertyDef } from './types'
|
||||
|
||||
const propsFromKinds = (...kinds: PropertyDef['kind'][]): PropertyDef[] =>
|
||||
kinds.map((kind, i) => ({
|
||||
id: `id-${i}`,
|
||||
name: `field_${i}`,
|
||||
kind,
|
||||
required: false,
|
||||
unique: false,
|
||||
}))
|
||||
|
||||
describe('SchemaBuilder', () => {
|
||||
it('показывает empty state когда полей нет', () => {
|
||||
const onChange = vi.fn()
|
||||
renderWithI18n(<SchemaBuilder properties={[]} onChange={onChange} />)
|
||||
expect(screen.getByText('Полей нет — добавь первое')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('добавляет новое поле через onChange при клике "Добавить поле"', async () => {
|
||||
const user = userEvent.setup()
|
||||
const onChange = vi.fn()
|
||||
renderWithI18n(<SchemaBuilder properties={[]} onChange={onChange} />)
|
||||
|
||||
await user.click(screen.getByRole('button', { name: /Добавить поле/i }))
|
||||
|
||||
expect(onChange).toHaveBeenCalledTimes(1)
|
||||
const next = onChange.mock.calls[0][0] as PropertyDef[]
|
||||
expect(next).toHaveLength(1)
|
||||
expect(next[0]).toMatchObject({ name: '', kind: 'string', required: false, unique: false })
|
||||
expect(next[0].id).toBeTruthy()
|
||||
})
|
||||
|
||||
it('рендерит N PropertyEditor по числу properties', () => {
|
||||
const onChange = vi.fn()
|
||||
renderWithI18n(
|
||||
<SchemaBuilder properties={propsFromKinds('string', 'integer', 'enum')} onChange={onChange} />,
|
||||
)
|
||||
// По 1 заголовку "Поле #N" на каждый property.
|
||||
expect(screen.getByText('Поле #1')).toBeInTheDocument()
|
||||
expect(screen.getByText('Поле #2')).toBeInTheDocument()
|
||||
expect(screen.getByText('Поле #3')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('moveUp поднимает property вверх', async () => {
|
||||
const user = userEvent.setup()
|
||||
const onChange = vi.fn()
|
||||
const initial = propsFromKinds('string', 'integer')
|
||||
renderWithI18n(<SchemaBuilder properties={initial} onChange={onChange} />)
|
||||
|
||||
const upButtons = screen.getAllByRole('button', { name: /Выше/i })
|
||||
await user.click(upButtons[1])
|
||||
|
||||
expect(onChange).toHaveBeenCalledTimes(1)
|
||||
const next = onChange.mock.calls[0][0] as PropertyDef[]
|
||||
expect(next[0].kind).toBe('integer')
|
||||
expect(next[1].kind).toBe('string')
|
||||
})
|
||||
|
||||
it('moveUp на первом элементе — no-op (kbd disabled, onChange не вызывается)', async () => {
|
||||
const user = userEvent.setup()
|
||||
const onChange = vi.fn()
|
||||
renderWithI18n(<SchemaBuilder properties={propsFromKinds('string', 'integer')} onChange={onChange} />)
|
||||
|
||||
const upButtons = screen.getAllByRole('button', { name: /Выше/i })
|
||||
expect(upButtons[0]).toBeDisabled()
|
||||
await user.click(upButtons[0])
|
||||
expect(onChange).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('moveDown на последнем — disabled', () => {
|
||||
const onChange = vi.fn()
|
||||
renderWithI18n(<SchemaBuilder properties={propsFromKinds('string', 'integer')} onChange={onChange} />)
|
||||
const downButtons = screen.getAllByRole('button', { name: /Ниже/i })
|
||||
expect(downButtons[1]).toBeDisabled()
|
||||
})
|
||||
|
||||
it('removeAt удаляет указанный property', async () => {
|
||||
const user = userEvent.setup()
|
||||
const onChange = vi.fn()
|
||||
const initial = propsFromKinds('string', 'integer', 'enum')
|
||||
renderWithI18n(<SchemaBuilder properties={initial} onChange={onChange} />)
|
||||
|
||||
const deleteButtons = screen.getAllByRole('button', { name: /Удалить/i })
|
||||
await user.click(deleteButtons[1])
|
||||
|
||||
const next = onChange.mock.calls[0][0] as PropertyDef[]
|
||||
expect(next).toHaveLength(2)
|
||||
expect(next.map((p) => p.kind)).toEqual(['string', 'enum'])
|
||||
})
|
||||
})
|
||||
Reference in New Issue
Block a user