diff --git a/.github/workflows/component-tests.yml b/.github/workflows/component-tests.yml new file mode 100644 index 00000000..a51dc31e --- /dev/null +++ b/.github/workflows/component-tests.yml @@ -0,0 +1,62 @@ +name: Component tests + +on: + pull_request: + push: + branches: [main] + +permissions: + contents: read + +jobs: + component-tests: + runs-on: ubuntu-latest + timeout-minutes: 25 + + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-node@v4 + with: + node-version: 20 + cache: npm + + - run: npm ci + + - run: npx playwright install --with-deps chromium + + # Baseline создаётся первым прогоном и переиспользуется в следующих. + - uses: actions/cache@v4 + with: + path: | + .storybook/style-baselines + .storybook/a11y-baseline + .storybook/pixel-baselines + e2e/baselines + key: component-baselines-${{ runner.os }}-${{ github.ref_name }} + restore-keys: | + component-baselines-${{ runner.os }}- + + - name: Storybook + тесты + run: | + npx ng run angular-ui-kit:storybook --port 6007 --no-open > /tmp/storybook.log 2>&1 & + for i in $(seq 1 60); do + if curl -fsS http://localhost:6007/iframe.html >/dev/null 2>&1; then break; fi + sleep 3 + done + curl -fsS http://localhost:6007/iframe.html >/dev/null + + node e2e/build-registry.mjs + node e2e/builtin-all.mjs + node e2e/all.mjs --theme=light + + - name: Артефакты + if: always() + uses: actions/upload-artifact@v4 + with: + name: component-tests + if-no-files-found: ignore + path: | + e2e/reports + e2e/artifacts + /tmp/storybook.log diff --git a/.gitignore b/.gitignore index fafd8dce..966347ea 100644 --- a/.gitignore +++ b/.gitignore @@ -61,3 +61,12 @@ src/assets/components/themes .claude/* .qwen .worktrees/ + +# e2e tooling artifacts and generated baselines +/e2e/reports/ +/e2e/artifacts/ +/e2e/baselines/ +/e2e/registry.json +/.storybook/style-baselines/ +/.storybook/a11y-baseline/ +/.storybook/pixel-baselines/ diff --git a/.storybook/test-runner.ts b/.storybook/test-runner.ts new file mode 100644 index 00000000..a9adb2de --- /dev/null +++ b/.storybook/test-runner.ts @@ -0,0 +1,415 @@ +import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { dirname, join, resolve } from 'node:path'; +import { getViolations, injectAxe } from 'axe-playwright'; +import { toMatchImageSnapshot } from 'jest-image-snapshot'; +import { getStoryContext, waitForPageReady, type TestRunnerConfig } from '@storybook/test-runner'; + +/** + * Снапшоты вычисленных стилей вместо пиксельных скриншотов. + * + * Слепок снимается с элементов, размеченных PrimeNG (`data-pc-section`), — это стабильная + * семантическая карта компонента. Дифф читается как «padding-top: 12px → 10px» и не зависит + * от шрифтов, сглаживания и ОС. + * + * Каждая story снимается в трёх вариантах: `light` (десктоп, светлая тема), `dark` и `mobile`. + * `light` хранится целиком, `dark` и `mobile` — только отличия от него: тёмная тема меняет + * цвета, мобильный вьюпорт — единицы свойств, и хранить ради этого три полных копии незачем. + * + * Baseline в репозиторий не кладётся — как пиксельные снимки и долг axe: 783 файла слепка + * не код, а состояние на момент прогона. Первый прогон на чистой копии снимает его сам, + * дальше сверяется с ним; правку токенов видно в диффе следующего прогона. + * + * Пересобрать осознанно: UPDATE_STYLE_BASELINES=1 npm run test-storybook + */ + +type Page = Parameters>[0]; + +/** `expect` приходит из jest-окружения раннера, отдельного импорта у него нет. */ +declare const expect: ((received: unknown) => { + toMatchImageSnapshot: (options: Record) => void; +}) & { extend: (matchers: Record) => void }; +type StyleSnapshot = Record>; + +/** + * Корень baseline можно вынести наружу (например, для матричного прогона e2e), + * чтобы не перезаписывать рабочие снимки и не ловить их дрейф. + */ +const BASELINE_ROOT = process.env['STORYBOOK_BASELINE_ROOT'] + ? resolve(process.cwd(), process.env['STORYBOOK_BASELINE_ROOT']) + : join(process.cwd(), '.storybook'); +const BASELINE_DIR = join(BASELINE_ROOT, 'style-baselines'); +const UPDATE = process.env['UPDATE_STYLE_BASELINES'] === '1'; + +const PIXEL_BASELINE_DIR = join(BASELINE_ROOT, 'pixel-baselines'); +const CLIP_PADDING = 4; +const A11Y_BASELINE_DIR = join(BASELINE_ROOT, 'a11y-baseline'); +const UPDATE_A11Y = process.env['UPDATE_A11Y_BASELINE'] === '1'; + +const MOBILE_VIEWPORT = { width: 390, height: 844 }; + +/** + * Story, снимок которых нестабилен по своей природе. Лента миниатюр галереи перерисовывается + * вместе с позицией карусели: часть элементов остаётся свёрнутой в нулевую высоту, и какие + * именно — от прогона к прогону разное. Снимок адресует повторы по порядку в DOM, поэтому там + * он не воспроизводится; геометрию галереи покрывают остальные её stories. + */ +const STYLE_SNAPSHOT_SKIP = ['components-media-galleria--thumbnails']; + +/** + * Компоненты, для которых снимаем ещё и пиксели: тень карточки, пунктир разделителя, форма + * аватара, градиент скелетона, иконка внутри бейджа/тега/чипа — вычисленные стили этого + * не описывают. Остальным хватает снимка стилей: он дешевле и не привязан к ОС. + * + * Baseline этих снимков в репозиторий не кладётся: рендер шрифтов в macOS и в образе CI + * различается, и общий baseline не совпал бы ни там, ни там. Первый локальный прогон + * создаёт снимки сам, дальше сверяется с ними. + */ +const PIXEL_SNAPSHOT_TITLES = [ + 'Components/Panel/Card', + 'Components/Panel/Divider', + 'Components/Misc/Avatar', + 'Components/Misc/Skeleton', + 'Components/Misc/Badge', + 'Components/Misc/Tag', + 'Components/Misc/Chip' +]; +const SETTLE_TIMEOUT = 2000; + +/** + * Блокируют прогон только нарушения, которые реально мешают пользоваться компонентом. + * `moderate` и `minor` axe тоже находит, но там много спорного — их не гейтим. + */ +const BLOCKING_A11Y_IMPACTS = ['critical', 'serious']; + +const TRACKED_PROPERTIES = [ + 'padding-top', + 'padding-right', + 'padding-bottom', + 'padding-left', + 'height', + 'min-height', + 'font-size', + 'line-height', + 'font-weight', + 'border-top-left-radius', + 'border-top-right-radius', + 'border-bottom-right-radius', + 'border-bottom-left-radius', + 'border-top-width', + 'border-right-width', + 'border-bottom-width', + 'border-left-width', + 'gap', + 'color', + 'background-color', + 'border-top-color' +]; + +/** + * Тема переключается классом на `` — так же, как это делает `withThemeByClassName` + * в `preview.ts`, и именно этот селектор ждёт PrimeNG (`darkModeSelector: '.dark'`). + */ +const VARIANTS: { name: string; apply: (page: Page) => Promise; reset: (page: Page) => Promise }[] = [ + { + name: 'light', + apply: async () => undefined, + reset: async () => undefined + }, + { + name: 'dark', + apply: (page) => page.evaluate(() => document.documentElement.classList.add('dark')), + reset: (page) => page.evaluate(() => document.documentElement.classList.remove('dark')) + }, + { + name: 'mobile', + apply: (page) => page.setViewportSize(MOBILE_VIEWPORT), + reset: async () => undefined + } +]; + +/** + * Ждём, пока раскладка перестанет меняться: `waitForPageReady` закрывает загрузку шрифтов и + * сети, но ленивые картинки и анимации раскрытия доезжают позже, и снимок ловит промежуточную + * геометрию (`height: 0px` у превью галереи). Сигнатура опрашивается по кадрам, пока не совпадёт + * дважды подряд. + */ +const settleLayout = (timeout: number): Promise => + new Promise((resolve) => { + const root = document.querySelector('#storybook-root'); + // Подпись собирается по тем же элементам, что попадут в снимок: у галереи превью лежат + // в контейнере фиксированной высоты, поэтому размеры страницы не меняются, пока картинки + // догружаются, — общая геометрия страницы такую гонку не ловит. + const signature = () => + root + ? [ + document.images.length - [...document.images].filter((image) => image.complete).length, + ...[...root.querySelectorAll('[data-pc-section]')].map((element) => + Math.round(element.getBoundingClientRect().height) + ) + ].join(',') + : ''; + + const deadline = performance.now() + timeout; + let previous = signature(); + let stable = 0; + + const tick = () => { + const current = signature(); + stable = current === previous ? stable + 1 : 0; + previous = current; + + if (stable >= 2 || performance.now() > deadline) resolve(); + else requestAnimationFrame(tick); + }; + + requestAnimationFrame(tick); + }); + +const collectStyles = (properties: string[]): StyleSnapshot => { + const root = document.querySelector('#storybook-root'); + if (!root) return {}; + + const snapshot: StyleSnapshot = {}; + const seen = new Map(); + + root.querySelectorAll('[data-pc-section]').forEach((element) => { + const name = element.getAttribute('data-pc-name') ?? element.tagName.toLowerCase(); + const base = `${name}/${element.getAttribute('data-pc-section')}`; + const repeat = seen.get(base) ?? 0; + seen.set(base, repeat + 1); + + const computed = getComputedStyle(element); + snapshot[repeat === 0 ? base : `${base}[${repeat}]`] = Object.fromEntries( + properties.map((property) => [property, computed.getPropertyValue(property)]) + ); + }); + + return snapshot; +}; + +/** Свойства варианта, которые отличаются от `light`. Элементы с полным совпадением опускаются. */ +const deltaFromBase = (base: StyleSnapshot, variant: StyleSnapshot): StyleSnapshot => { + const delta: StyleSnapshot = {}; + + for (const [key, properties] of Object.entries(variant)) { + const changed = Object.entries(properties).filter(([property, value]) => base[key]?.[property] !== value); + if (changed.length > 0) delta[key] = Object.fromEntries(changed); + } + + return delta; +}; + +const diff = (baseline: StyleSnapshot, actual: StyleSnapshot): string[] => { + const changes: string[] = []; + + for (const key of new Set([...Object.keys(baseline), ...Object.keys(actual)])) { + const expectedProperties = baseline[key] ?? {}; + const receivedProperties = actual[key] ?? {}; + + for (const property of new Set([...Object.keys(expectedProperties), ...Object.keys(receivedProperties)])) { + const expected = expectedProperties[property] ?? '= light'; + const received = receivedProperties[property] ?? '= light'; + if (expected !== received) changes.push(`${key} · ${property}: ${expected} → ${received}`); + } + } + + return changes; +}; + +const compareWithBaseline = (file: string, actual: StyleSnapshot): string[] => { + if (UPDATE || !existsSync(file)) { + mkdirSync(dirname(file), { recursive: true }); + writeFileSync(file, `${JSON.stringify(actual, null, 2)}\n`, 'utf8'); + return []; + } + + return diff(JSON.parse(readFileSync(file, 'utf8')) as StyleSnapshot, actual); +}; + +const formatFailure = (context: { title: string; name: string }, issues: string[]): string => + [ + `Проверки story «${context.title} / ${context.name}» не прошли:`, + ...issues.map((issue) => ` ${issue}`), + '', + 'Если расхождение стилей ожидаемое: UPDATE_STYLE_BASELINES=1 npm run test-storybook' + ].join('\n'); + +/** + * Нарушения доступности от axe — в том же формате, что и расхождения стилей. + * + * Гейтить всё сразу нельзя: на момент подключения axe находил `critical`/`serious` в 129 из 264 + * stories — это накопленный долг PrimeNG и обёрток, его не закрыть одним PR. Поэтому известные + * правила ложатся в `.storybook/a11y-baseline/.json` и прогон падает только на + * **новом** нарушении. Список ведётся по id правила, без числа элементов, чтобы baseline + * не дёргался от каждой правки разметки. + * + * Baseline в репозиторий не кладётся: 129 файлов — снимок чужого долга, а не код кита. + * Первый прогон на чистой копии снимает его сам, дальше сверяется с ним. + * + * Пересобрать после починки: UPDATE_A11Y_BASELINE=1 npm run test-storybook + */ +const collectA11yIssues = async (page: Page, storyId: string, options: unknown): Promise => { + const violations = (await getViolations(page, '#storybook-root', options as never)).filter((violation) => + BLOCKING_A11Y_IMPACTS.includes(violation.impact ?? '') + ); + + const baselineFile = join(A11Y_BASELINE_DIR, `${storyId}.json`); + + if (UPDATE_A11Y || !existsSync(baselineFile)) { + const rules = [...new Set(violations.map((violation) => violation.id))].sort(); + + if (rules.length === 0) rmSync(baselineFile, { force: true }); + else { + mkdirSync(A11Y_BASELINE_DIR, { recursive: true }); + writeFileSync(baselineFile, `${JSON.stringify(rules, null, 2)}\n`, 'utf8'); + } + + return []; + } + + const known: string[] = JSON.parse(readFileSync(baselineFile, 'utf8')); + + return violations + .filter((violation) => !known.includes(violation.id)) + .map( + (violation) => `[a11y/${violation.impact}] ${violation.id}: ${violation.help} (${violation.nodes.length} элем.)` + ); +}; + +/** + * Пиксельный снимок — только для того, что вычисленные стили не описывают: теней, пунктира, + * формы стрелки, градиента скелетона. Список компонентов — в `PIXEL_SNAPSHOT_TITLES`. + * + * Baseline привязан к ОС и рендеру шрифтов: снятый на macOS не совпадёт с Linux в CI. Гонять + * генерацию и сверку нужно в одном окружении — в CI это образ `mcr.microsoft.com/playwright`. + */ +const FROZEN_ANIMATIONS = `*, *::before, *::after { + animation: none !important; + transition: none !important; + caret-color: transparent !important; +}`; + +/** + * Область снимка считается сама: у горизонтального разделителя `#storybook-root` имеет нулевую + * высоту (линию рисует `::before`), и `locator.screenshot()` на таком элементе просто виснет, + * ожидая, когда тот станет видимым. Поэтому берём объединение прямоугольников корня и всех его + * потомков, расширяем на несколько пикселей и снимаем обычным клипом. + */ +const snapshotClip = (padding: number) => { + const root = document.querySelector('#storybook-root'); + if (!root) return null; + + const rects = [root, ...root.querySelectorAll('*')].map((element) => element.getBoundingClientRect()); + const left = Math.min(...rects.map((rect) => rect.left)); + const top = Math.min(...rects.map((rect) => rect.top)); + const right = Math.max(...rects.map((rect) => rect.right)); + const bottom = Math.max(...rects.map((rect) => rect.bottom)); + + return { + x: Math.max(0, Math.floor(left) - padding), + y: Math.max(0, Math.floor(top) - padding), + width: Math.min(window.innerWidth, Math.ceil(right - left) + padding * 2), + height: Math.min(window.innerHeight, Math.ceil(bottom - top) + padding * 2) + }; +}; + +/** + * `complete` у картинки означает «загружена», но не «раскодирована и отрисована»: снимок аватара + * успевал захватить кадр без изображения. `decode()` дожидается готовности к отрисовке. + */ +const decodeImages = (): Promise => + Promise.all([...document.images].map((image) => image.decode().catch(() => undefined))); + +const capturePixelSnapshot = async (page: Page, storyId: string): Promise => { + await page.addStyleTag({ content: FROZEN_ANIMATIONS }); + await page.evaluate(decodeImages); + await page.evaluate(settleLayout, SETTLE_TIMEOUT); + + const clip = await page.evaluate(snapshotClip, CLIP_PADDING); + if (!clip || clip.width < 1 || clip.height < 1) return ['[pixel] нечего снимать: у story нулевая область']; + + const image = await page.screenshot({ clip }); + const baselinePath = join(PIXEL_BASELINE_DIR, `${storyId}.png`); + if (!existsSync(baselinePath)) { + mkdirSync(PIXEL_BASELINE_DIR, { recursive: true }); + writeFileSync(baselinePath, image); + } + + expect(image).toMatchImageSnapshot({ + customSnapshotsDir: PIXEL_BASELINE_DIR, + customDiffDir: join(PIXEL_BASELINE_DIR, '__diff__'), + customSnapshotIdentifier: storyId, + failureThreshold: 0.01, + failureThresholdType: 'percent' + }); + + return []; +}; + +const config: TestRunnerConfig = { + setup() { + expect.extend({ toMatchImageSnapshot }); + }, + + async preVisit(page) { + await injectAxe(page); + }, + + async postVisit(page, context) { + const { parameters } = await getStoryContext(page, context); + const issues: string[] = []; + + if (!parameters['a11y']?.disable) { + issues.push(...(await collectA11yIssues(page, context.id, parameters['a11y']?.options))); + } + + if (STYLE_SNAPSHOT_SKIP.includes(context.id)) { + if (issues.length > 0) throw new Error(formatFailure(context, issues)); + return; + } + + const desktopViewport = page.viewportSize(); + const snapshots = new Map(); + + for (const variant of VARIANTS) { + await variant.apply(page); + await waitForPageReady(page); + await page.evaluate(settleLayout, SETTLE_TIMEOUT); + snapshots.set(variant.name, await page.evaluate(collectStyles, TRACKED_PROPERTIES)); + await variant.reset(page); + } + + if (desktopViewport) await page.setViewportSize(desktopViewport); + + const base = snapshots.get('light') as StyleSnapshot; + if (Object.keys(base).length === 0) return; + + const changes: string[] = []; + + for (const [name, snapshot] of snapshots) { + const elementsDiffer = name !== 'light' && Object.keys(snapshot).join() !== Object.keys(base).join(); + + if (elementsDiffer) { + changes.push(`${name}: набор элементов не совпадает с light — вариант меняет разметку, а не только стили`); + continue; + } + + const payload = name === 'light' ? base : deltaFromBase(base, snapshot); + changes.push( + ...compareWithBaseline(join(BASELINE_DIR, name, `${context.id}.json`), payload).map( + (change) => `[${name}] ${change}` + ) + ); + } + + issues.push(...changes); + + if (PIXEL_SNAPSHOT_TITLES.includes(context.title)) { + issues.push(...(await capturePixelSnapshot(page, context.id))); + } + + if (issues.length > 0) throw new Error(formatFailure(context, issues)); + } +}; + +export default config; diff --git a/e2e/README.md b/e2e/README.md new file mode 100644 index 00000000..19ba551e --- /dev/null +++ b/e2e/README.md @@ -0,0 +1,28 @@ +# E2E компонентов + +Браузерные тесты Storybook-компонентов на Playwright: поведение, клавиатура, состояния, +доступность. Дополняют встроенный Storybook test-runner, не заменяют его. + +```bash +npm ci +npx playwright install chromium + +npm run storybook -- --port 6007 # отдельный терминал +npm run test:component -- select # Storybook при необходимости поднимется сам +npm run test:e2e # все e2e-спеки +npm run test:e2e:builtin # встроенный runner по всем компонентам +``` + +Точечно: + +```bash +node e2e/check.mjs select +node e2e/run.mjs select +node e2e/storybook-runner.mjs inputtext -- --maxWorkers=2 +``` + +- Спеки: `e2e/specs/.e2e.mjs`. +- Отчёты: `e2e/reports/`, скриншоты падений: `e2e/artifacts/`. +- Baseline создаётся первым прогоном; обновление — `UPDATE_STYLE_BASELINES=1`. +- В `main` 52 спеки: `image` добавляется после мержа PR #200. +- CI: `.github/workflows/component-tests.yml`. diff --git a/e2e/all.mjs b/e2e/all.mjs new file mode 100644 index 00000000..89ceacf0 --- /dev/null +++ b/e2e/all.mjs @@ -0,0 +1,44 @@ +#!/usr/bin/env node +/** + * Прогон всех e2e-спек подряд. + * + * Запуск: node e2e/all.mjs [--url=...] [--theme=light,dark] [--grep=...] [--headed] + * + * Каждая спека — отдельный процесс и отдельный браузер: падение одной не мешает + * остальным, а итоговая сводка собирается по кодам возврата. + */ +import { readdirSync } from 'node:fs'; +import { dirname, join, resolve } from 'node:path'; +import { spawnSync } from 'node:child_process'; +import { fileURLToPath } from 'node:url'; +import { log } from './lib/log.mjs'; + +const __dirname = dirname(fileURLToPath(import.meta.url)); +const ROOT = resolve(__dirname, '..'); +const passThrough = process.argv.slice(2); + +const specs = readdirSync(join(__dirname, 'specs')) + .filter((file) => file.endsWith('.e2e.mjs')) + .map((file) => file.replace(/\.e2e\.mjs$/, '')) + .sort(); + +const results = []; + +for (const spec of specs) { + log(`\n${'='.repeat(72)}\n${spec}\n${'='.repeat(72)}`); + const result = spawnSync(process.execPath, [join(ROOT, 'e2e/run.mjs'), spec, ...passThrough], { + cwd: ROOT, + stdio: 'inherit' + }); + results.push({ spec, code: result.status ?? 1 }); +} + +const failed = results.filter((result) => result.code !== 0); + +log(`\n${'='.repeat(72)}`); +log(`Спек: ${results.length}, успешно: ${results.length - failed.length}, с падениями: ${failed.length}`); +for (const result of results) { + log(` ${result.code === 0 ? '✓' : '✗'} ${result.spec}`); +} + +process.exit(failed.length > 0 ? 1 : 0); diff --git a/e2e/build-registry.mjs b/e2e/build-registry.mjs new file mode 100644 index 00000000..8362d756 --- /dev/null +++ b/e2e/build-registry.mjs @@ -0,0 +1,97 @@ +#!/usr/bin/env node +/** + * Реестр компонентов для e2e-работ: stories, группа, ветка. + * + * Источник stories — живой index.json Storybook (не storybook-static: он отстаёт). + * Ветка выбирается по конвенции `feature/--figma-sync`; если её нет — + * следующие варианты, иначе `branch: null` и компонент попадает в список нерешённых. + * + * Запуск: node e2e/build-registry.mjs [--url=http://localhost:6007] + * Результат: e2e/registry.json + */ +import { execFileSync } from 'node:child_process'; +import { existsSync, readdirSync, writeFileSync } from 'node:fs'; +import { dirname, join, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { log } from './lib/log.mjs'; + +const __dirname = dirname(fileURLToPath(import.meta.url)); +const ROOT = resolve(__dirname, '..'); + +const urlArg = process.argv.find((arg) => arg.startsWith('--url=')); +const baseUrl = (urlArg ? urlArg.slice('--url='.length) : 'http://localhost:6007').replace(/\/+$/, ''); + +const index = await (await fetch(`${baseUrl}/index.json`)).json(); +const componentsOnDisk = new Set( + readdirSync(join(ROOT, 'src/lib/components')).filter((name) => existsSync(join(ROOT, 'src/lib/components', name))) +); +const branches = execFileSync('git', ['branch', '--format=%(refname:short)'], { cwd: ROOT, encoding: 'utf8' }) + .split('\n') + .filter(Boolean); + +const groupFromTitle = (title) => { + const parts = String(title).split('/'); + return parts.length > 2 ? parts[1].toLowerCase() : 'components'; +}; + +const branchFor = (component, group) => { + const candidates = [ + `feature/${group}-${component}-figma-sync`, + `feature/${component}-figma-sync`, + `feature/${component}`, + component, + `e2e/${component}` + ]; + return candidates.find((candidate) => branches.includes(candidate)) ?? null; +}; + +const byComponent = new Map(); + +for (const entry of Object.values(index.entries ?? {})) { + if (entry.type === 'docs') continue; + + const importPath = entry.importPath ?? ''; + const fromPath = importPath.match(/src\/stories\/components\/([^/]+)\//)?.[1]; + const component = fromPath ?? String(entry.title).split('/').pop().toLowerCase(); + if (!componentsOnDisk.has(component)) continue; + + if (!byComponent.has(component)) { + byComponent.set(component, { + component, + title: entry.title, + group: groupFromTitle(entry.title), + stories: [] + }); + } + + byComponent.get(component).stories.push({ id: entry.id, name: entry.name }); +} + +const registry = [...byComponent.values()] + .map((item) => { + item.stories.sort((a, b) => a.name.localeCompare(b.name)); + return { + ...item, + branch: branchFor(item.component, item.group), + storyCount: item.stories.length + }; + }) + .sort((a, b) => a.component.localeCompare(b.component)); + +const unresolved = registry.filter((item) => !item.branch); +const payload = { + generatedAt: new Date().toISOString(), + storybook: baseUrl, + total: registry.length, + unresolved: unresolved.map((item) => item.component), + components: registry +}; + +writeFileSync(join(__dirname, 'registry.json'), `${JSON.stringify(payload, null, 2)}\n`); + +log(`Компонентов: ${registry.length}, stories: ${registry.reduce((sum, item) => sum + item.storyCount, 0)}`); +log(`Без ветки: ${unresolved.length}${unresolved.length ? ` — ${unresolved.map((item) => item.component).join(', ')}` : ''}`); +log('\nКомпонент Stories Ветка'); +for (const item of registry) { + log(`${item.component.padEnd(18)} ${String(item.storyCount).padStart(4)} ${item.branch ?? '—'}`); +} diff --git a/e2e/build-status.mjs b/e2e/build-status.mjs new file mode 100644 index 00000000..66c2be9c --- /dev/null +++ b/e2e/build-status.mjs @@ -0,0 +1,99 @@ +#!/usr/bin/env node +/** + * Собирает e2e/STATUS.md из реестра, спек, отчётов и локальных коммитов. + * + * Запуск: node e2e/build-status.mjs + */ +import { execFileSync } from 'node:child_process'; +import { existsSync, readFileSync, writeFileSync } from 'node:fs'; +import { dirname, join, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { log } from './lib/log.mjs'; + +const __dirname = dirname(fileURLToPath(import.meta.url)); +const ROOT = resolve(__dirname, '..'); + +const registry = JSON.parse(readFileSync(join(__dirname, 'registry.json'), 'utf8')); +const WAVES = { + 'static': ['avatar', 'badge', 'card', 'chip', 'divider', 'skeleton', 'progressbar', 'progressspinner', 'tag', 'timeline', 'breadcrumb', 'message', 'metergroup'], + 'form': ['checkbox', 'radiobutton', 'toggleswitch', 'togglebutton', 'select-button', 'inputmask', 'inputnumber', 'inputotp', 'password', 'textarea', 'slider', 'rating', 'inputgroup', 'inputtext', 'select', 'date-picker', 'autocomplete', 'multiselect', 'listbox'], + 'overlay': ['dialog', 'drawer', 'popover', 'tooltip', 'toast', 'confirm-dialog', 'menu', 'menubar', 'megamenu', 'panelmenu', 'tieredmenu', 'tabs', 'stepper', 'accordion', 'scroll-panel', 'fileupload'], + 'media': ['carousel', 'galleria', 'image', 'paginator', 'button'] +}; + +const waveOf = (component) => Object.entries(WAVES).find(([, list]) => list.includes(component))?.[0] ?? 'other'; + +const readJson = (file) => { + try { + return JSON.parse(readFileSync(file, 'utf8')); + } catch { + return null; + } +}; + +const commitFor = (component) => { + try { + return execFileSync('git', ['log', '--all', '--format=%h', '--grep', `test(${component}): добавить e2e-спеку`, '-1'], { + cwd: ROOT, + encoding: 'utf8' + }).trim(); + } catch { + return ''; + } +}; + +const rows = registry.components.map((item) => { + const spec = existsSync(join(__dirname, 'specs', `${item.component}.e2e.mjs`)); + const e2e = readJson(join(__dirname, 'reports', `${item.component}-e2e.json`)); + const builtin = readJson(join(__dirname, 'reports', 'builtin', `${item.component}.json`)); + + const e2eSummary = e2e ? `${e2e.summary.passed}/${e2e.summary.total}${e2e.summary.failed ? ` ✗${e2e.summary.failed}` : ''}` : '—'; + const builtinSummary = builtin ? `${builtin.numPassedTests}/${builtin.numTotalTests}${builtin.numFailedTests ? ` ✗${builtin.numFailedTests}` : ''}` : '—'; + + return { + ...item, + wave: waveOf(item.component), + spec, + e2eSummary, + builtinSummary, + commit: commitFor(item.component) + }; +}); + +const status = (row) => { + if (!row.spec) return 'ожидает'; + if (row.e2eSummary === '—') return 'спека'; + if (row.e2eSummary.includes('✗')) return 'падает'; + if (row.builtinSummary.includes('✗')) return 'builtin ✗'; + if (row.commit) return 'готово'; + return 'спека ок'; +}; + +const lines = [ + '# E2E STATUS', + '', + `Обновлено: ${new Date().toISOString()}`, + '', + `Компонентов: ${rows.length}, stories: ${rows.reduce((sum, row) => sum + row.storyCount, 0)}.`, + '', + 'Статусы: `ожидает` — нет спеки; `спека` — спека есть, прогона нет; `спека ок` — e2e зелёный, коммита нет;', + '`builtin ✗` — падает встроенный раннер; `падает` — падает e2e; `готово` — e2e и builtin зелёные, коммит в ветке есть.', + '', + '| Компонент | Волна | Stories | Спека | e2e | builtin | Ветка | Коммит | Статус |', + '|---|---|---|---|---|---|---|---|---|' +]; + +for (const row of rows.sort((a, b) => a.component.localeCompare(b.component))) { + lines.push( + `| ${row.component} | ${row.wave} | ${row.storyCount} | ${row.spec ? '✓' : '—'} | ${row.e2eSummary} | ${row.builtinSummary} | ${row.branch ?? '—'} | ${row.commit ? `\`${row.commit}\`` : '—'} | ${status(row)} |` + ); +} + +const byWave = Object.fromEntries(Object.keys(WAVES).map((wave) => [wave, rows.filter((row) => row.wave === wave).length])); +lines.push('', `Волны: ${Object.entries(byWave).map(([wave, count]) => `${wave} — ${count}`).join(', ')}.`, ''); + +const done = rows.filter((row) => status(row) === 'готово').length; +lines.push(`Готово: ${done} из ${rows.length}.`, ''); + +writeFileSync(join(__dirname, 'STATUS.md'), `${lines.join('\n')}\n`); +log(`STATUS.md: ${rows.length} компонентов, готово ${done}`); diff --git a/e2e/builtin-all.mjs b/e2e/builtin-all.mjs new file mode 100644 index 00000000..e3c31015 --- /dev/null +++ b/e2e/builtin-all.mjs @@ -0,0 +1,109 @@ +#!/usr/bin/env node +/** + * Прогон встроенного Storybook test-runner по каждому компоненту из реестра. + * + * На компонент: обёртка e2e/storybook-runner.mjs (фильтрация index.json) + JSON-отчёт + * в e2e/reports/builtin/.json. Сводка — e2e/reports/builtin-summary.json. + * + * Запуск: node e2e/builtin-all.mjs [--only=select,button] [--limit=3] [--url=...] + */ +import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'; +import { spawnSync } from 'node:child_process'; +import { dirname, join, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { log } from './lib/log.mjs'; + +const __dirname = dirname(fileURLToPath(import.meta.url)); +const ROOT = resolve(__dirname, '..'); +const args = process.argv.slice(2); +const onlyArg = args.find((arg) => arg.startsWith('--only=')); +const only = onlyArg ? new Set(onlyArg.slice('--only='.length).split(',').map((value) => value.trim())) : null; +const limitArg = args.find((arg) => arg.startsWith('--limit=')); +const limit = limitArg ? Number(limitArg.slice('--limit='.length)) : Infinity; +const urlArg = args.find((arg) => arg.startsWith('--url=')); +const url = urlArg ? urlArg.slice('--url='.length) : 'http://localhost:6007'; + +const registryPath = join(__dirname, 'registry.json'); +if (!existsSync(registryPath)) { + const build = spawnSync(process.execPath, [join(__dirname, 'build-registry.mjs')], { cwd: ROOT, stdio: 'inherit' }); + if (build.status !== 0) process.exit(build.status ?? 1); +} +const registry = JSON.parse(readFileSync(registryPath, 'utf8')); +const reportsDir = join(__dirname, 'reports/builtin'); +mkdirSync(reportsDir, { recursive: true }); + +let components = registry.components; +if (only) components = components.filter((item) => only.has(item.component)); +components = components.slice(0, limit); + +const results = []; + +for (const item of components) { + const reportPath = join(reportsDir, `${item.component}.json`); + const started = Date.now(); + process.stdout.write(`${item.component.padEnd(18)} `); + + const run = spawnSync( + process.execPath, + [ + join(__dirname, 'storybook-runner.mjs'), + item.component, + `--url=${url}`, + '--', + '--maxWorkers=2', + '--json', + '--outputFile', + reportPath + ], + { + cwd: ROOT, + encoding: 'utf8', + maxBuffer: 20 * 1024 * 1024, + // Свежие baseline в отдельном каталоге: не трогаем рабочие снимки и их дрейф. + env: { ...process.env, STORYBOOK_BASELINE_ROOT: 'e2e/baselines' } + } + ); + + let summary = { passed: 0, failed: 0, total: 0 }; + try { + const report = JSON.parse(readFileSync(reportPath, 'utf8')); + summary = { + passed: report.numPassedTests ?? 0, + failed: report.numFailedTests ?? 0, + total: report.numTotalTests ?? 0 + }; + } catch { + /* отчёт не создан — ниже это видно по коду возврата */ + } + + const duration = Date.now() - started; + const status = run.status === 0 ? 'ok' : `fail(${run.status})`; + log(`${status} ${summary.passed}/${summary.total} ${duration}ms`); + + results.push({ + component: item.component, + branch: item.branch, + exitCode: run.status, + duration, + ...summary, + report: reportPath, + stderr: run.status === 0 ? undefined : (run.stderr ?? '').split('\n').filter(Boolean).slice(-20) + }); +} + +const failed = results.filter((result) => result.exitCode !== 0); +const payload = { + generatedAt: new Date().toISOString(), + url, + total: results.length, + failed: failed.length, + results +}; + +writeFileSync(join(__dirname, 'reports/builtin-summary.json'), `${JSON.stringify(payload, null, 2)}\n`); + +log(`\nКомпонентов: ${results.length}, успешно: ${results.length - failed.length}, с падениями: ${failed.length}`); +if (failed.length > 0) { + for (const result of failed) log(` ✗ ${result.component} (exit ${result.exitCode})`); + process.exit(1); +} diff --git a/e2e/check.mjs b/e2e/check.mjs new file mode 100644 index 00000000..585e8b2b --- /dev/null +++ b/e2e/check.mjs @@ -0,0 +1,214 @@ +#!/usr/bin/env node +/** + * Одна команда на компонент: поднять Storybook (если нужно), прогнать встроенный + * test-runner и e2e-спеку, собрать общий отчёт. + * + * node e2e/check.mjs button + * node e2e/check.mjs select --theme=light,dark + * node e2e/check.mjs button --spec=button-demo --fresh-baselines + * node e2e/check.mjs button --no-builtin + * + * Отчёт: e2e/reports/-check.json. Exit code 1 — есть падения. + */ +import { spawn, spawnSync } from 'node:child_process'; +import { existsSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { dirname, join, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { log } from './lib/log.mjs'; + +const __dirname = dirname(fileURLToPath(import.meta.url)); +const ROOT = resolve(__dirname, '..'); + +const argv = process.argv.slice(2); +if (argv.includes('--help') || argv.includes('-h')) { + log(`Usage: node e2e/check.mjs [options] + +Одна команда: Storybook (если нужно) + встроенный test-runner + e2e. + +Options: + --spec= e2e-спека, по умолчанию имя компонента + --theme=light,dark темы e2e, по умолчанию light + --url= адрес Storybook, по умолчанию http://localhost:6007 + --port= порт, если --url не задан + --no-builtin пропустить встроенный test-runner + --no-e2e пропустить e2e + --no-start-storybook не поднимать Storybook автоматически + --fresh-baselines baseline во временном каталоге`); + process.exit(0); +} + +const component = argv.find((arg) => !arg.startsWith('-')); +if (!component) { + console.error('Укажите компонент: node e2e/check.mjs [--spec=...] [--url=...]'); + process.exit(2); +} + +const flag = (name, fallback = undefined) => { + const prefix = `--${name}=`; + const found = argv.find((arg) => arg.startsWith(prefix)); + return found ? found.slice(prefix.length) : fallback; +}; +const has = (name) => argv.includes(`--${name}`); + +const port = Number(flag('port', '6007')); +const baseUrl = (flag('url', `http://localhost:${port}`) || '').replace(/\/+$/, ''); +const spec = flag('spec', component); +const theme = flag('theme', 'light'); +const skipBuiltin = has('no-builtin'); +const skipE2e = has('no-e2e'); +const noStart = has('no-start-storybook'); +const freshBaselines = has('fresh-baselines'); + +const reportsDir = join(__dirname, 'reports'); +const builtinReport = join(reportsDir, `${component}-builtin-runner.json`); +const e2eReport = join(reportsDir, `${spec}-e2e.json`); +const checkReport = join(reportsDir, `${component}-check.json`); + +const sleep = (ms) => new Promise((resolveSleep) => setTimeout(resolveSleep, ms)); + +const isUp = async () => { + try { + return (await fetch(`${baseUrl}/iframe.html`, { signal: AbortSignal.timeout(1500) })).ok; + } catch { + return false; + } +}; + +let storybook = null; +const stopStorybook = () => { + if (!storybook || storybook.killed) return; + try { + process.kill(-storybook.pid, 'SIGTERM'); + } catch { + storybook.kill('SIGTERM'); + } + storybook = null; +}; + +const startStorybook = async () => { + if (await isUp()) return false; + if (noStart) { + console.error(`Storybook не запущен на ${baseUrl}. Уберите --no-start-storybook или поднимите его вручную.`); + process.exit(2); + } + + log(`Storybook не запущен — поднимаю на :${port}…`); + storybook = spawn( + process.platform === 'win32' ? 'npx.cmd' : 'npx', + ['ng', 'run', 'angular-ui-kit:storybook', '--port', String(port), '--no-open'], + { cwd: ROOT, detached: true, stdio: ['ignore', 'ignore', 'ignore'] } + ); + + const started = Date.now(); + while (Date.now() - started < 180_000) { + if (await isUp()) { + log(`Storybook готов за ${Math.round((Date.now() - started) / 1000)} с`); + return true; + } + if (storybook.exitCode !== null) { + console.error('Storybook завершился с ошибкой. Запустите вручную: npm run storybook -- --port ' + port); + process.exit(2); + } + await sleep(1500); + } + + console.error('Storybook не поднялся за 180 с.'); + stopStorybook(); + process.exit(2); +}; + +const resolveTitle = async () => { + const response = await fetch(`${baseUrl}/index.json`); + if (!response.ok) throw new Error(`index.json: HTTP ${response.status}`); + const index = await response.json(); + const entries = Object.values(index.entries ?? {}).filter((entry) => entry.type !== 'docs'); + const normalized = component.toLowerCase().replace(/[^a-z0-9]/g, ''); + const exact = entries.filter((entry) => { + const last = String(entry.title ?? '').split('/').pop() ?? ''; + return last.toLowerCase().replace(/[^a-z0-9]/g, '') === normalized; + }); + if (exact.length === 0) throw new Error(`в Storybook нет stories компонента «${component}»`); + return { title: exact[0].title, count: exact.length }; +}; + +const result = { + component, + spec, + baseUrl, + generatedAt: new Date().toISOString(), + builtin: { status: 'skipped' }, + e2e: { status: 'skipped' } +}; + +const run = async () => { + const startedStorybook = await startStorybook(); + + try { + const { title } = await resolveTitle(); + log(`\nКомпонент: ${component} (${title})`); + + if (!skipBuiltin) { + log('\n── Storybook test-runner ─────────────────────────'); + const baselineRoot = freshBaselines ? mkdtempSync(join(tmpdir(), 'e2e-baselines-')) : join(__dirname, 'baselines'); + const runArgs = [ + join(__dirname, 'storybook-runner.mjs'), + title, + `--url=${baseUrl}`, + '--', + '--maxWorkers=2', + '--json', + '--outputFile', + builtinReport + ]; + + const child = spawnSync(process.execPath, runArgs, { + cwd: ROOT, + stdio: 'inherit', + env: { ...process.env, STORYBOOK_BASELINE_ROOT: baselineRoot } + }); + result.builtin = { status: child.status === 0 ? 'passed' : 'failed', exitCode: child.status, report: builtinReport }; + } + + if (!skipE2e) { + const specFile = join(__dirname, 'specs', `${spec}.e2e.mjs`); + if (!existsSync(specFile)) { + log(`\n── E2E ────────────────────────────────────────────`); + log(`Спека ${spec}.e2e.mjs не найдена — пропускаю e2e.`); + result.e2e = { status: 'skipped', reason: 'spec-not-found' }; + } else { + log('\n── E2E ────────────────────────────────────────────'); + const child = spawnSync(process.execPath, [join(__dirname, 'run.mjs'), spec, `--theme=${theme}`], { + cwd: ROOT, + stdio: 'inherit' + }); + result.e2e = { status: child.status === 0 ? 'passed' : 'failed', exitCode: child.status, report: e2eReport }; + } + } + } finally { + if (startedStorybook) stopStorybook(); + } + + result.generatedAt = new Date().toISOString(); + writeFileSync(checkReport, `${JSON.stringify(result, null, 2)}\n`); + + log('\n── Итог ───────────────────────────────────────────'); + log(`builtin: ${result.builtin.status}${result.builtin.exitCode !== undefined ? ` (exit ${result.builtin.exitCode})` : ''}`); + log(`e2e: ${result.e2e.status}${result.e2e.exitCode !== undefined ? ` (exit ${result.e2e.exitCode})` : ''}`); + log(`Отчёт: ${checkReport}`); + + process.exit([result.builtin, result.e2e].some((part) => part.status === 'failed') ? 1 : 0); +}; + +for (const signal of ['SIGINT', 'SIGTERM']) { + process.on(signal, () => { + stopStorybook(); + process.exit(130); + }); +} + +run().catch((error) => { + stopStorybook(); + console.error(error.message); + process.exit(2); +}); diff --git a/e2e/generate-specs.mjs b/e2e/generate-specs.mjs new file mode 100644 index 00000000..dc475074 --- /dev/null +++ b/e2e/generate-specs.mjs @@ -0,0 +1,104 @@ +#!/usr/bin/env node +/** + * Генерация smoke-спек для компонентов, у которых ещё нет e2e-спеки. + * + * Одна story = один тест: корень отрендерился, страница без pageerror. Плюс одна + * проверка тёмной темы на первую story. Глубокие сценарии (клавиатура, оверлеи, + * состояния) дописываются в спеку компонента вручную — генератор их не трогает. + * + * Запуск: node e2e/generate-specs.mjs [--only=avatar,card] [--force] + */ +import { existsSync, readFileSync, writeFileSync } from 'node:fs'; +import { dirname, join, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { log } from './lib/log.mjs'; + +const __dirname = dirname(fileURLToPath(import.meta.url)); +const ROOT = resolve(__dirname, '..'); +const REGISTRY = join(__dirname, 'registry.json'); +const SPECS = join(__dirname, 'specs'); + +const args = process.argv.slice(2); +const onlyArg = args.find((arg) => arg.startsWith('--only=')); +const only = onlyArg ? new Set(onlyArg.slice('--only='.length).split(',').map((value) => value.trim())) : null; +const force = args.includes('--force'); + +if (!existsSync(REGISTRY)) { + console.error('Нет e2e/registry.json. Сначала: node e2e/build-registry.mjs'); + process.exit(2); +} + +const registry = JSON.parse(readFileSync(REGISTRY, 'utf8')); +const MARKER = 'Сгенерировано e2e/generate-specs.mjs'; + +const slug = (value) => + value + .toLowerCase() + .replace(/[^a-z0-9]+/g, '-') + .replace(/^-+|-+$/g, '') || 'story'; + +const quote = (value) => JSON.stringify(value); +const storiesLiteral = (stories) => + ['[', ...stories.map((story) => ` { id: ${quote(story.id)}, name: ${quote(story.name)} },`), ']'].join('\n'); + +const specFor = (item) => { + const stories = item.stories.map((story) => ({ id: story.id, name: story.name })); + const first = stories[0]; + + const renderCheck = `run: async ({ page, expect, errors }) => { + const pageErrors = errors.filter((error) => error.type === 'pageerror'); + expect(pageErrors.map((error) => error.text), 'ошибки страницы').toEqual([]); + expect(await page.locator('#storybook-root > *').count(), 'корень story').toBeGreaterThan(0); + const box = await page.locator('#storybook-root').boundingBox(); + expect(Boolean(box && box.width > 0), 'ширина story').toBe(true); + }`; + + return `/** + * Smoke-спека «${item.component}»: все story рендерятся без pageerror, тёмная тема. + * + * ${MARKER}: глубокие сценарии (клавиатура, оверлеи, состояния) добавляются вручную. + */ + +const STORIES = ${storiesLiteral(stories)}; + +export default { + component: ${quote(item.component)}, + stories: Object.fromEntries(STORIES.map((story, index) => [\`story-\${index}\`, story.id])), + tests: [ + ...STORIES.map((story, index) => ({ + name: \`Smoke: \${story.name}\`, + story: \`story-\${index}\`, + ${renderCheck} + })), + { + name: \`Тёмная тема: \${STORIES[0].name}\`, + story: 'story-0', + theme: 'dark', + ${renderCheck} + } + ] +}; +`; +}; + +let created = 0; +let skipped = 0; + +for (const item of registry.components) { + if (only && !only.has(item.component)) continue; + + const file = join(SPECS, `${item.component}.e2e.mjs`); + if (existsSync(file)) { + const existing = readFileSync(file, 'utf8'); + if (!force || !existing.includes(MARKER)) { + skipped += 1; + continue; + } + } + + writeFileSync(file, specFor(item)); + created += 1; + log(`+ ${item.component} (${item.stories.length} stories)`); +} + +log(`\nСоздано: ${created}, пропущено (уже есть): ${skipped}`); diff --git a/e2e/lib/a11y.mjs b/e2e/lib/a11y.mjs new file mode 100644 index 00000000..f98e317d --- /dev/null +++ b/e2e/lib/a11y.mjs @@ -0,0 +1,56 @@ +/** + * Проверки доступности через axe-playwright. + * + * Гейтим только critical/serious: moderate и minor дают много спорных срабатываний + * на декоративных иконках и контрасте второстепенного текста. + */ +import { getViolations, injectAxe } from 'axe-playwright'; + +const DEFAULT_IMPACTS = ['critical', 'serious']; + +export async function scanA11y(page, { include, exclude, impacts = DEFAULT_IMPACTS, rules } = {}) { + const context = {}; + if (include) context.include = [include]; + if (exclude) context.exclude = [exclude]; + + const options = { resultTypes: ['violations'] }; + + // Storybook addon-a11y тоже запускает axe на рендере story. Если сканы пересеклись, + // axe кидает «Axe is already running» — ждём и повторяем, это гонка инструментов. + const violations = await runWithRetry(async () => { + await injectAxe(page); + if (rules) options.rules = rules; + return getViolations(page, Object.keys(context).length ? context : undefined, options); + }); + + return violations + .filter((violation) => impacts.includes(violation.impact)) + .map((violation) => ({ + id: violation.id, + impact: violation.impact, + help: violation.help, + nodes: violation.nodes.map((node) => ({ + target: node.target, + html: node.html, + failureSummary: node.failureSummary + })) + })); +} + +async function runWithRetry(action, attempts = 3) { + let lastError; + for (let attempt = 0; attempt < attempts; attempt += 1) { + try { + return await action(); + } catch (error) { + lastError = error; + if (!/already running/i.test(error.message)) throw error; + await new Promise((resolve) => setTimeout(resolve, 400 * (attempt + 1))); + } + } + throw lastError; +} + +/** Короткое представление нарушений для сообщения об ошибке. */ +export const formatViolations = (violations) => + violations.map((violation) => `${violation.impact} ${violation.id}: ${violation.help}`).join('; '); diff --git a/e2e/lib/dom.mjs b/e2e/lib/dom.mjs new file mode 100644 index 00000000..0ea9c555 --- /dev/null +++ b/e2e/lib/dom.mjs @@ -0,0 +1,35 @@ +/** Частые DOM-чтения в одну строку, чтобы спека читалась как сценарий. */ + +export const count = (page, selector) => page.locator(selector).count(); + +export const exists = async (page, selector) => (await page.locator(selector).count()) > 0; + +export const visible = (page, selector) => page.locator(selector).first().isVisible(); + +export const text = (page, selector) => page.locator(selector).first().innerText(); + +export const attr = (page, selector, name) => page.locator(selector).first().getAttribute(name); + +export const computed = (page, selector, property) => + page.locator(selector).first().evaluate((element, prop) => getComputedStyle(element).getPropertyValue(prop), property); + +export const box = (page, selector) => page.locator(selector).first().boundingBox(); + +/** Что реально в фокусе: тег, классы, id и ARIA-роль. */ +export const focused = (page) => + page.evaluate(() => { + const element = document.activeElement; + if (!element || element === document.body) return { tag: 'BODY', className: '', id: '', role: null }; + return { + tag: element.tagName, + className: typeof element.className === 'string' ? element.className : '', + id: element.id, + role: element.getAttribute('role') + }; + }); + +/** Видимые элементы по селектору — для проверок списков, где часть скрыта фильтром. */ +export const visibleTexts = (page, selector) => + page.locator(selector).evaluateAll((elements) => + elements.filter((element) => element.offsetParent !== null).map((element) => element.textContent.trim()) + ); diff --git a/e2e/lib/expect.mjs b/e2e/lib/expect.mjs new file mode 100644 index 00000000..123c6064 --- /dev/null +++ b/e2e/lib/expect.mjs @@ -0,0 +1,75 @@ +/** + * Минимальные ассерты для e2e без @playwright/test. + * + * Сообщение всегда содержит имя проверяемого значения, ожидание и факт — по нему + * можно починить тест, не открывая отчёт. + */ + +export class AssertionError extends Error { + constructor(message) { + super(message); + this.name = 'AssertionError'; + } +} + +const stringify = (value) => { + if (typeof value === 'string') return JSON.stringify(value); + if (typeof value === 'function') return String(value); + try { + return JSON.stringify(value); + } catch { + return String(value); + } +}; + +const deepEqual = (a, b) => { + if (Object.is(a, b)) return true; + if (typeof a !== 'object' || typeof b !== 'object' || a === null || b === null) return false; + if (Array.isArray(a) !== Array.isArray(b)) return false; + const ak = Object.keys(a); + const bk = Object.keys(b); + if (ak.length !== bk.length) return false; + return ak.every((key) => deepEqual(a[key], b[key])); +}; + +export function expect(actual, label = 'значение') { + const fail = (expected, hint = '') => { + throw new AssertionError(`${label}: ожидалось ${expected}, получено ${stringify(actual)}${hint ? ` (${hint})` : ''}`); + }; + + return { + toBe(expected) { + if (!Object.is(actual, expected)) fail(stringify(expected)); + }, + toEqual(expected) { + if (!deepEqual(actual, expected)) fail(stringify(expected)); + }, + toBeTruthy() { + if (!actual) fail('truthy'); + }, + toBeFalsy() { + if (actual) fail('falsy'); + }, + toContain(expected) { + const ok = typeof actual === 'string' ? actual.includes(expected) : Array.isArray(actual) && actual.includes(expected); + if (!ok) fail(`содержащее ${stringify(expected)}`); + }, + toMatch(regexp) { + if (!regexp.test(String(actual))) fail(`соответствующее ${regexp}`); + }, + toBeGreaterThan(expected) { + if (!(actual > expected)) fail(`> ${expected}`); + }, + toBeGreaterThanOrEqual(expected) { + if (!(actual >= expected)) fail(`>= ${expected}`); + }, + toBeLessThan(expected) { + if (!(actual < expected)) fail(`< ${expected}`); + }, + toBeLessThanOrEqual(expected) { + if (!(actual <= expected)) fail(`<= ${expected}`); + } + }; +} + +export const isAssertionError = (error) => error instanceof AssertionError; diff --git a/e2e/lib/log.mjs b/e2e/lib/log.mjs new file mode 100644 index 00000000..8070d4bc --- /dev/null +++ b/e2e/lib/log.mjs @@ -0,0 +1,2 @@ +/** Единая точка вывода CLI-скриптов. */ +export const log = (...args) => process.stdout.write(`${args.join(' ')}\n`); diff --git a/e2e/lib/poll.mjs b/e2e/lib/poll.mjs new file mode 100644 index 00000000..1fbcfb8d --- /dev/null +++ b/e2e/lib/poll.mjs @@ -0,0 +1,44 @@ +/** + * Ожидание асинхронного условия с понятным сообщением об ошибке. + * + * Playwright-локторы умеют ждать сами, но состояние PrimeNG (оверлей, фокус, значение) + * удобнее проверять одной функцией и получать последнее фактическое значение в тексте ошибки. + */ + +export class TimeoutError extends Error { + constructor(message) { + super(message); + this.name = 'TimeoutError'; + } +} + +export async function poll(check, { timeout = 3000, interval = 50, label = 'условие' } = {}) { + const started = Date.now(); + let lastValue; + let lastError; + + while (Date.now() - started < timeout) { + try { + const value = await check(); + if (value) return value; + lastValue = value; + } catch (error) { + lastError = error; + } + await new Promise((resolve) => setTimeout(resolve, interval)); + } + + const elapsed = Date.now() - started; + const details = lastError ? `последняя ошибка: ${lastError.message}` : `последнее значение: ${JSON.stringify(lastValue)}`; + throw new TimeoutError(`${label}: не дождались за ${elapsed}ms (${details})`); +} + +/** Ждёт, пока функция вернёт true, и возвращает её значение (для цепочек). */ +export async function waitForValue(read, options) { + let value; + await poll(async () => { + value = await read(); + return value; + }, options); + return value; +} diff --git a/e2e/lib/storybook.mjs b/e2e/lib/storybook.mjs new file mode 100644 index 00000000..82bec13e --- /dev/null +++ b/e2e/lib/storybook.mjs @@ -0,0 +1,96 @@ +/** + * Открытие story в Storybook и ожидание готовности Angular-рендера. + * + * Storybook отдаёт каждую story в iframe.html без менеджера, поэтому страница — + * сразу целевой документ: оверлеи PrimeNG (appendTo body) и фокус видны без обхода iframe. + */ + +export const DEFAULT_STORYBOOK_URL = process.env.E2E_STORYBOOK_URL || 'http://localhost:6007'; + +export function normalizeBaseUrl(url) { + return String(url || DEFAULT_STORYBOOK_URL).replace(/\/+$/, ''); +} + +/** + * URL story. `args` передаются строкой Storybook (`key:value,key2:value2`), + * тема — через globals аддона themes (`theme:dark`). + */ +export function storyUrl(baseUrl, { id, theme = 'light', args, viewMode = 'story' } = {}) { + if (!id) throw new Error('storyUrl: не передан id story'); + const url = new URL(`${normalizeBaseUrl(baseUrl)}/iframe.html`); + url.searchParams.set('id', id); + url.searchParams.set('viewMode', viewMode); + if (theme) url.searchParams.set('globals', `theme:${theme}`); + if (args) url.searchParams.set('args', args); + return url.toString(); +} + +const settle = async (page) => { + await page.evaluate( + () => + new Promise((resolve) => { + requestAnimationFrame(() => requestAnimationFrame(resolve)); + }) + ); + await page.waitForTimeout(50); +}; + +export function collectPageErrors(page) { + const errors = []; + page.on('pageerror', (error) => errors.push({ type: 'pageerror', text: error.message })); + page.on('console', (message) => { + if (message.type() === 'error') errors.push({ type: 'console', text: message.text() }); + }); + return errors; +} + +/** + * Переход на story и ожидание, что Angular отрисовал непустой корень. + * Возвращает `errors` — накопленные ошибки страницы и консоли. + */ +export async function openStory(page, baseUrl, options = {}) { + const errors = collectPageErrors(page); + const timeout = options.timeout ?? 20000; + + await page.goto(storyUrl(baseUrl, options), { waitUntil: 'domcontentloaded', timeout }); + // Корень может быть нулевой высоты (горизонтальный разделитель) — ждём attached, не visible. + await page.waitForSelector('#storybook-root', { state: 'attached', timeout }); + + if (await page.locator('.sb-show-errordisplay').isVisible().catch(() => false)) { + const message = (await page.locator('body').innerText()).slice(0, 300); + throw new Error(`Storybook не отрендерил story: ${message}`); + } + + // Пустой корень — story ещё компилируется/монтируется; нулевая высота — упавший рендер. + await page.waitForFunction( + () => { + const root = document.querySelector('#storybook-root'); + if (!root || root.children.length === 0) return false; + const rect = root.getBoundingClientRect(); + // Высота может быть нулевой у горизонтального разделителя: линию рисует border/::before. + return rect.width > 0; + }, + undefined, + { timeout } + ); + + await page.evaluate(() => document.fonts.ready); + await settle(page); + + if (options.waitFor) { + await page.waitForSelector(options.waitFor, { timeout }); + await settle(page); + } + + return { errors }; +} + +/** Корень story — единственная точка монтирования, не зависит от менеджера. */ +export const storyRoot = (page) => page.locator('#storybook-root'); + +export async function setTheme(page, theme) { + await page.evaluate((next) => { + document.documentElement.classList.toggle('dark', next === 'dark'); + }, theme); + await settle(page); +} diff --git a/e2e/run.mjs b/e2e/run.mjs new file mode 100644 index 00000000..52ce4ee7 --- /dev/null +++ b/e2e/run.mjs @@ -0,0 +1,240 @@ +#!/usr/bin/env node +/** + * Раннер e2e-тестов компонентов на Storybook. + * + * Запуск: + * node e2e/run.mjs select + * node e2e/run.mjs select --url=http://localhost:6007 --theme=light,dark + * node e2e/run.mjs select --grep=клавиатура --headed + * + * Спека — `e2e/specs/.e2e.mjs` с default-экспортом: + * { component, stories: { default: 'components-form-select--default' }, tests: [...] } + * + * Каждый тест получает свой browser context: состояние одной проверки не влияет + * на другую. Отчёт пишется в `e2e/reports/-e2e.json`, скриншоты + * падений — в `e2e/artifacts//`. + */ +import { mkdirSync, writeFileSync } from 'node:fs'; +import { dirname, join, resolve } from 'node:path'; +import { fileURLToPath, pathToFileURL } from 'node:url'; +import { chromium } from 'playwright'; + +import { scanA11y, formatViolations } from './lib/a11y.mjs'; +import { expect } from './lib/expect.mjs'; +import { poll } from './lib/poll.mjs'; +import { DEFAULT_STORYBOOK_URL, normalizeBaseUrl, openStory, storyUrl } from './lib/storybook.mjs'; +import { focused } from './lib/dom.mjs'; +import { log } from './lib/log.mjs'; + +const __dirname = dirname(fileURLToPath(import.meta.url)); +const ROOT = resolve(__dirname, '..'); + +const args = process.argv.slice(2); +const component = args.find((arg) => !arg.startsWith('-')); +const flag = (name, fallback = undefined) => { + const prefix = `--${name}=`; + const found = args.find((arg) => arg.startsWith(prefix)); + return found ? found.slice(prefix.length) : fallback; +}; +const has = (name) => args.includes(`--${name}`); + +if (!component) { + console.error('Укажите компонент: node e2e/run.mjs [--url=...] [--theme=light,dark] [--grep=...] [--headed]'); + process.exit(2); +} + +const baseUrl = normalizeBaseUrl(flag('url', DEFAULT_STORYBOOK_URL)); +const themes = (flag('theme', 'light') || 'light').split(',').map((theme) => theme.trim()).filter(Boolean); +const grep = flag('grep'); +const headed = has('headed'); +const timeout = Number(flag('timeout', '30000')); + +const specPath = join(__dirname, 'specs', `${component}.e2e.mjs`); +let spec; +try { + spec = (await import(pathToFileURL(specPath).href)).default; +} catch (error) { + console.error(`Не удалось загрузить спеку ${specPath}: ${error.message}`); + process.exit(2); +} + +const stories = spec.stories ?? {}; +const resolveStory = (test) => { + if (test.story && typeof test.story === 'object') return test.story; + const id = stories[test.story] ?? test.story; + if (!id) throw new Error(`Тест «${test.name}»: не найдена story «${test.story}»`); + return { id, args: test.args }; +}; + +const selected = (spec.tests ?? []).filter((test) => { + if (grep && !test.name.toLowerCase().includes(grep.toLowerCase())) return false; + return true; +}); + +if (selected.length === 0) { + console.error(`В спеке ${component} нет тестов под фильтр «${grep ?? ''}»`); + process.exit(2); +} + +const slug = (value) => + value + .toLowerCase() + .replace(/[^a-zа-я0-9]+/gi, '-') + .replace(/^-+|-+$/g, '') + .slice(0, 80); + +const reportsDir = join(__dirname, 'reports'); +const artifactsDir = join(__dirname, 'artifacts', component); +mkdirSync(reportsDir, { recursive: true }); +mkdirSync(artifactsDir, { recursive: true }); + +const browser = await chromium.launch({ headless: !headed }); +const results = []; +let failed = 0; +let skipped = 0; + +const contextFor = async (test) => { + const context = await browser.newContext({ + viewport: test.viewport ?? { width: 1280, height: 800 }, + locale: 'ru-RU', + timezoneId: 'Europe/Moscow' + }); + return context; +}; + +const runTest = async (test, theme) => { + const started = Date.now(); + const story = resolveStory(test); + const name = theme === 'light' ? test.name : `${test.name} [${theme}]`; + const testSlug = `${slug(test.name)}${theme === 'light' ? '' : `-${theme}`}`; + const context = await contextFor(test); + const page = await context.newPage(); + page.setDefaultTimeout(timeout); + + const consoleErrors = []; + page.on('pageerror', (error) => consoleErrors.push(`pageerror: ${error.message}`)); + page.on('console', (message) => { + if (message.type() === 'error') consoleErrors.push(`console: ${message.text()}`); + }); + + let pageErrors = []; + + try { + const opened = await openStory(page, baseUrl, { + id: story.id, + theme, + args: story.args, + timeout, + waitFor: test.waitFor + }); + pageErrors = opened.errors; + + const ctx = { + page, + theme, + expect: (actual, label) => expect(actual, label), + wait: (check, options) => poll(check, { timeout, label: test.name, ...options }), + a11y: (options) => scanA11y(page, options), + formatViolations, + focused: () => focused(page), + errors: pageErrors, + url: storyUrl(baseUrl, { id: story.id, theme, args: story.args }), + test + }; + + await test.run(ctx); + + const duration = Date.now() - started; + results.push({ + name, + story: story.id, + theme, + status: 'passed', + duration, + consoleErrors, + pageErrors, + note: test.knownIssue ? 'известный дефект больше не воспроизводится' : undefined + }); + log(` ✓ ${name} (${duration}ms)${test.knownIssue ? ' — дефект больше не воспроизводится' : ''}`); + return true; + } catch (error) { + const known = Boolean(test.knownIssue); + if (!known) failed += 1; + const duration = Date.now() - started; + const screenshot = join(artifactsDir, `${testSlug}.png`); + try { + await page.screenshot({ path: screenshot, fullPage: false }); + } catch { + /* страница могла закрыться — скриншот не критичен */ + } + results.push({ + name, + story: story.id, + theme, + status: known ? 'known' : 'failed', + duration, + knownIssue: test.knownIssue, + error: { message: error.message, stack: error.stack?.split('\n').slice(0, 6).join('\n') }, + screenshot, + consoleErrors, + pageErrors + }); + log(` ${known ? '!' : '✗'} ${name} (${duration}ms)${known ? ' — известный дефект' : ''}`); + log(` ${error.message.split('\n')[0]}`); + if (error.stack && process.env.E2E_VERBOSE) log(error.stack); + return false; + } finally { + await context.close(); + } +}; + +log(`\nE2E ${component} · Storybook ${baseUrl} · темы: ${themes.join(', ')}`); + +for (const test of selected) { + if (test.skip) { + skipped += 1; + results.push({ name: test.name, status: 'skipped', reason: test.skip }); + log(` - ${test.name} (skip: ${test.skip})`); + continue; + } + + const testThemes = test.theme ? [test.theme] : themes; + for (const theme of testThemes) { + await runTest(test, theme); + } +} + +await browser.close(); + +const passed = results.filter((result) => result.status === 'passed').length; +const failedResults = results.filter((result) => result.status === 'failed'); +const knownResults = results.filter((result) => result.status === 'known'); +const report = { + component, + baseUrl, + generatedAt: new Date().toISOString(), + summary: { total: results.length, passed, failed, skipped, known: knownResults.length }, + results +}; + +const reportPath = join(reportsDir, `${component}-e2e.json`); +writeFileSync(reportPath, `${JSON.stringify(report, null, 2)}\n`); + +log(`\nИтого: ${passed} passed, ${failed} failed, ${knownResults.length} known, ${skipped} skipped`); +log(`Отчёт: ${reportPath}`); + +if (knownResults.length > 0) { + log('\nИзвестные дефекты (не блокируют прогон):'); + for (const result of knownResults) { + log(`- ${result.name}: ${result.error.message.split('\n')[0]}`); + } +} + +if (failedResults.length > 0) { + log('\nПадения:'); + for (const result of failedResults) { + log(`- ${result.name}: ${result.error.message.split('\n')[0]}`); + if (result.screenshot) log(` ${result.screenshot}`); + } + process.exit(1); +} diff --git a/e2e/specs/accordion.e2e.mjs b/e2e/specs/accordion.e2e.mjs new file mode 100644 index 00000000..da5a635c --- /dev/null +++ b/e2e/specs/accordion.e2e.mjs @@ -0,0 +1,74 @@ +/** + * E2E-спека Accordion: раскрытие, режим multiple, disabled и клавиатура. + */ + +const STORIES = [ + { id: 'components-panel-accordion--default', name: 'Default' }, + { id: 'components-panel-accordion--disabled', name: 'Disabled' }, + { id: 'components-panel-accordion--multiple', name: 'Multiple' }, + { id: 'components-panel-accordion--slots', name: 'Slots' } +]; + +const smoke = (story) => ({ + name: `Smoke: ${story.name}`, + story: story.id, + run: async ({ page, expect, errors }) => { + expect(errors.filter((error) => error.type === 'pageerror').map((error) => error.text), 'ошибки страницы').toEqual([]); + expect(await page.locator('#storybook-root > *').count(), 'корень story').toBeGreaterThan(0); + const box = await page.locator('#storybook-root').boundingBox(); + expect(Boolean(box && box.width > 0), 'ширина story').toBe(true); + } +}); + +const expanded = (page) => + page.locator('.p-accordionheader').evaluateAll((headers) => headers.map((header) => header.getAttribute('aria-expanded'))); + +export default { + component: 'accordion', + stories: Object.fromEntries(STORIES.map((story) => [story.id, story.id])), + tests: [ + { + name: 'Default: один раскрытый раздел, клик переключает', + story: 'components-panel-accordion--default', + run: async ({ page, expect }) => { + expect(await page.locator('.p-accordionheader').count(), 'заголовки').toBe(3); + expect(await expanded(page), 'начальное состояние').toEqual(['true', 'false', 'false']); + + await page.locator('.p-accordionheader').nth(1).click(); + expect(await expanded(page), 'после клика').toEqual(['false', 'true', 'false']); + } + }, + { + name: 'Multiple: раскрываются все три раздела', + story: 'components-panel-accordion--multiple', + run: async ({ page, expect }) => { + expect(await expanded(page), 'начальное состояние').toEqual(['true', 'false', 'true']); + await page.locator('.p-accordionheader').nth(1).click(); + expect(await expanded(page), 'после клика').toEqual(['true', 'true', 'true']); + } + }, + { + name: 'Disabled: недоступный раздел не раскрывается', + story: 'components-panel-accordion--disabled', + run: async ({ page, expect }) => { + const disabled = page.locator('.p-accordionheader[aria-disabled=true]'); + expect(await disabled.count(), 'disabled-заголовок').toBe(1); + const before = await disabled.getAttribute('aria-expanded'); + await disabled.click({ force: true }); + expect(await disabled.getAttribute('aria-expanded'), 'после клика').toBe(before); + } + }, + { + name: 'Keyboard: Enter раскрывает раздел', + story: 'components-panel-accordion--default', + run: async ({ page, expect }) => { + const header = page.locator('.p-accordionheader').nth(1); + await header.focus(); + await page.keyboard.press('Enter'); + expect(await header.getAttribute('aria-expanded'), 'после Enter').toBe('true'); + } + }, + ...STORIES.map(smoke), + { ...smoke(STORIES[0]), name: `Smoke: ${STORIES[0].name} (тёмная тема)`, theme: 'dark' } + ] +}; diff --git a/e2e/specs/autocomplete.e2e.mjs b/e2e/specs/autocomplete.e2e.mjs new file mode 100644 index 00000000..3c91c9c7 --- /dev/null +++ b/e2e/specs/autocomplete.e2e.mjs @@ -0,0 +1,144 @@ +/** + * E2E-спека AutoComplete: подсказки, выбор, dropdown, multiple, очистка и a11y. + */ + +const STORIES = [ + { id: 'components-form-autocomplete--clearable', name: 'Clearable' }, + { id: 'components-form-autocomplete--default', name: 'Default' }, + { id: 'components-form-autocomplete--disabled', name: 'Disabled' }, + { id: 'components-form-autocomplete--dropdown', name: 'Dropdown' }, + { id: 'components-form-autocomplete--invalid', name: 'Invalid' }, + { id: 'components-form-autocomplete--labels', name: 'Labels' }, + { id: 'components-form-autocomplete--multiple', name: 'Multiple' }, + { id: 'components-form-autocomplete--objects', name: 'Objects' } +]; + +const smoke = (story) => ({ + name: `Smoke: ${story.name}`, + story: story.id, + run: async ({ page, expect, errors }) => { + expect(errors.filter((error) => error.type === 'pageerror').map((error) => error.text), 'ошибки страницы').toEqual([]); + expect(await page.locator('#storybook-root > *').count(), 'корень story').toBeGreaterThan(0); + const box = await page.locator('#storybook-root').boundingBox(); + expect(Boolean(box && box.width > 0), 'ширина story').toBe(true); + } +}); + +export default { + component: 'autocomplete', + stories: Object.fromEntries(STORIES.map((story) => [story.id, story.id])), + tests: [ + { + name: 'Default: ввод открывает подсказки и выбор заполняет поле', + story: 'components-form-autocomplete--default', + run: async ({ page, expect, wait }) => { + const input = page.locator('input.p-autocomplete-input'); + expect(await input.getAttribute('role'), 'role').toBe('combobox'); + expect(await input.getAttribute('aria-expanded'), 'до ввода').toBe('false'); + + await input.fill('Мо'); + await wait(async () => (await page.locator('.p-autocomplete-option').count()) > 0); + expect(await input.getAttribute('aria-expanded'), 'после ввода').toBe('true'); + expect(await page.locator('.p-autocomplete-option').first().innerText(), 'подсказка').toBe('Москва'); + + await page.locator('.p-autocomplete-option').first().click(); + expect(await input.inputValue(), 'значение').toBe('Москва'); + } + }, + { + name: 'Keyboard: ArrowDown и Enter выбирают подсказку', + story: 'components-form-autocomplete--default', + run: async ({ page, expect, wait }) => { + const input = page.locator('input.p-autocomplete-input'); + await input.fill('Мо'); + await wait(async () => (await page.locator('.p-autocomplete-option').count()) > 0); + await page.keyboard.press('ArrowDown'); + await page.keyboard.press('Enter'); + expect(await input.inputValue(), 'значение после Enter').toBe('Москва'); + } + }, + { + name: 'Dropdown: кнопка открывает все восемь вариантов', + story: 'components-form-autocomplete--dropdown', + run: async ({ page, expect }) => { + await page.locator('.p-autocomplete-dropdown').click(); + await page.waitForSelector('.p-autocomplete-option'); + expect(await page.locator('.p-autocomplete-option').count(), 'варианты').toBe(8); + expect(await page.locator('input').first().getAttribute('aria-expanded'), 'aria-expanded').toBe('true'); + } + }, + { + name: 'Multiple: выбранный вариант становится чипом', + story: 'components-form-autocomplete--multiple', + run: async ({ page, expect, wait }) => { + const input = page.locator('input.p-autocomplete-input'); + await input.fill('Мо'); + await wait(async () => (await page.locator('.p-autocomplete-option').count()) > 0); + await page.locator('.p-autocomplete-option').first().click(); + expect(await page.locator('.p-autocomplete-chip').count(), 'чип').toBe(1); + expect(await page.locator('#storybook-root').innerText(), 'текст чипа').toContain('Москва'); + } + }, + { + name: 'Clearable: иконка очищает значение', + story: 'components-form-autocomplete--clearable', + run: async ({ page, expect }) => { + const input = page.locator('input.p-autocomplete-input').first(); + expect(await page.locator('.p-autocomplete-clear-icon').count(), 'иконка очистки').toBe(1); + await page.locator('.p-autocomplete-clear-icon').click(); + expect(await input.inputValue(), 'значение после очистки').toBe(''); + } + }, + { + name: 'Disabled: поле отключено и не открывает подсказки', + story: 'components-form-autocomplete--disabled', + run: async ({ page, expect }) => { + const input = page.locator('input.p-autocomplete-input'); + expect(await input.isDisabled(), 'disabled').toBe(true); + await input.click({ force: true }); + await page.waitForTimeout(300); + expect(await page.locator('.p-autocomplete-overlay').count(), 'оверлей').toBe(0); + } + }, + { + name: 'Invalid: класс p-invalid', + story: 'components-form-autocomplete--invalid', + run: async ({ page, expect }) => { + expect(await page.locator('input.p-autocomplete-input').getAttribute('class'), 'invalid').toContain('p-invalid'); + } + }, + { + name: 'Labels: лейбл связан с полем', + story: 'components-form-autocomplete--labels', + run: async ({ page, expect }) => { + const label = page.locator('label').first(); + expect(await label.getAttribute('for'), 'for').toBe(await page.locator('input').first().getAttribute('id')); + } + }, + { + name: 'Dropdown: у кнопки есть доступное имя', + story: 'components-form-autocomplete--dropdown', + knownIssue: 'p-autocomplete-dropdown — button без aria-label/текста: скринридер не называет кнопку', + run: async ({ page, expect }) => { + const name = await page.locator('.p-autocomplete-dropdown').evaluate((element) => { + return element.getAttribute('aria-label') || element.getAttribute('title') || element.textContent.trim(); + }); + expect(Boolean(name), 'доступное имя').toBe(true); + } + }, + { + name: 'Keyboard: активная подсказка объявляется через aria-activedescendant', + story: 'components-form-autocomplete--default', + knownIssue: 'PrimeNG не выставляет aria-activedescendant при навигации по подсказкам', + run: async ({ page, expect, wait }) => { + const input = page.locator('input.p-autocomplete-input'); + await input.fill('Мо'); + await wait(async () => (await page.locator('.p-autocomplete-option').count()) > 0); + await page.keyboard.press('ArrowDown'); + expect(await input.getAttribute('aria-activedescendant'), 'aria-activedescendant').toBeTruthy(); + } + }, + ...STORIES.map(smoke), + { ...smoke(STORIES[0]), name: `Smoke: ${STORIES[0].name} (тёмная тема)`, theme: 'dark' } + ] +}; diff --git a/e2e/specs/avatar.e2e.mjs b/e2e/specs/avatar.e2e.mjs new file mode 100644 index 00000000..3b1454b5 --- /dev/null +++ b/e2e/specs/avatar.e2e.mjs @@ -0,0 +1,86 @@ +/** + * E2E-спека Avatar: размеры, формы, группа и бейдж. + */ + +const STORIES = [ + { id: 'components-misc-avatar--default', name: 'Default' }, + { id: 'components-misc-avatar--group', name: 'Group' }, + { id: 'components-misc-avatar--icon', name: 'Icon' }, + { id: 'components-misc-avatar--icon-with-badge', name: 'Icon With Badge' }, + { id: 'components-misc-avatar--image', name: 'Image' }, + { id: 'components-misc-avatar--image-with-badge', name: 'Image With Badge' }, + { id: 'components-misc-avatar--label', name: 'Label' }, + { id: 'components-misc-avatar--label-with-badge', name: 'Label With Badge' }, + { id: 'components-misc-avatar--shapes', name: 'Shapes' }, + { id: 'components-misc-avatar--sizes', name: 'Sizes' } +]; + +const smoke = (story) => ({ + name: `Smoke: ${story.name}`, + story: story.id, + run: async ({ page, expect, errors }) => { + expect(errors.filter((error) => error.type === 'pageerror').map((error) => error.text), 'ошибки страницы').toEqual([]); + expect(await page.locator('#storybook-root > *').count(), 'корень story').toBeGreaterThan(0); + const box = await page.locator('#storybook-root').boundingBox(); + expect(Boolean(box && box.width > 0), 'ширина story').toBe(true); + } +}); + +export default { + component: 'avatar', + stories: Object.fromEntries(STORIES.map((story) => [story.id, story.id])), + tests: [ + { + name: 'Sizes: 32 < 40 < 56 и классы lg/xl', + story: 'components-misc-avatar--sizes', + run: async ({ page, expect }) => { + const items = await page.locator('.p-avatar').evaluateAll((elements) => + elements.map((element) => ({ className: element.className, size: Math.round(element.getBoundingClientRect().height) })) + ); + expect(items.length, 'количество аватаров').toBe(3); + expect(items[0].size < items[1].size, 'base ниже lg').toBe(true); + expect(items[1].size < items[2].size, 'lg ниже xl').toBe(true); + expect(items[1].className, 'класс lg').toContain('p-avatar-lg'); + expect(items[2].className, 'класс xl').toContain('p-avatar-xl'); + } + }, + { + name: 'Shapes: круглая форма через p-avatar-circle', + story: 'components-misc-avatar--shapes', + run: async ({ page, expect }) => { + const classes = await page.locator('.p-avatar').evaluateAll((elements) => elements.map((element) => element.className)); + expect(classes.length, 'количество аватаров').toBe(2); + expect(classes[1], 'круглый аватар').toContain('p-avatar-circle'); + } + }, + { + name: 'Group: несколько аватаров и счётчик +2', + story: 'components-misc-avatar--group', + run: async ({ page, expect }) => { + expect(await page.locator('.p-avatar-group').count(), 'группа').toBe(1); + expect(await page.locator('.p-avatar').count(), 'аватары в группе').toBeGreaterThanOrEqual(3); + expect(await page.locator('#storybook-root').innerText(), 'счётчик').toContain('+2'); + } + }, + { + name: 'Label With Badge: бейдж и изображение', + story: 'components-misc-avatar--image-with-badge', + run: async ({ page, expect }) => { + expect(await page.locator('.p-badge').count(), 'бейдж').toBeGreaterThanOrEqual(1); + expect(await page.locator('img').count(), 'изображения').toBeGreaterThan(0); + } + }, + { + name: 'Image: у изображения аватара есть alt', + story: 'components-misc-avatar--image', + knownIssue: 'PrimeNG p-avatar рендерит img без alt: изображение озвучивается как декоративное', + run: async ({ page, expect }) => { + const alts = await page.locator('img').evaluateAll((images) => images.map((image) => image.alt)); + expect(alts.length, 'изображения').toBeGreaterThan(0); + expect(alts.every((alt) => alt.trim().length > 0), 'у всех изображений есть alt').toBe(true); + } + }, + ...STORIES.map(smoke), + { ...smoke(STORIES[0]), name: `Smoke: ${STORIES[0].name} (тёмная тема)`, theme: 'dark' } + ] +}; diff --git a/e2e/specs/badge.e2e.mjs b/e2e/specs/badge.e2e.mjs new file mode 100644 index 00000000..7ad705d6 --- /dev/null +++ b/e2e/specs/badge.e2e.mjs @@ -0,0 +1,80 @@ +/** + * E2E-спека Badge: severity, размеры, точка и форма. + */ + +const STORIES = [ + { id: 'components-misc-badge--default', name: 'Default' }, + { id: 'components-misc-badge--dot', name: 'Dot' }, + { id: 'components-misc-badge--severity', name: 'Severity' }, + { id: 'components-misc-badge--sizes', name: 'Sizes' } +]; + +const smoke = (story) => ({ + name: `Smoke: ${story.name}`, + story: story.id, + run: async ({ page, expect, errors }) => { + expect(errors.filter((error) => error.type === 'pageerror').map((error) => error.text), 'ошибки страницы').toEqual([]); + expect(await page.locator('#storybook-root > *').count(), 'корень story').toBeGreaterThan(0); + const box = await page.locator('#storybook-root').boundingBox(); + expect(Boolean(box && box.width > 0), 'ширина story').toBe(true); + } +}); + +export default { + component: 'badge', + stories: Object.fromEntries(STORIES.map((story) => [story.id, story.id])), + tests: [ + { + name: 'Severity: классы info/success/warn/danger', + story: 'components-misc-badge--severity', + run: async ({ page, expect }) => { + const classes = await page.locator('.p-badge').evaluateAll((elements) => elements.map((element) => element.className)); + expect(classes.length, 'количество бейджей').toBe(5); + expect(classes[1], 'info').toContain('p-badge-info'); + expect(classes[2], 'success').toContain('p-badge-success'); + expect(classes[3], 'warn').toContain('p-badge-warn'); + expect(classes[4], 'danger').toContain('p-badge-danger'); + } + }, + { + name: 'Sizes: 24 < 28 < 32 и классы lg/xl', + story: 'components-misc-badge--sizes', + run: async ({ page, expect }) => { + const items = await page.locator('.p-badge').evaluateAll((elements) => + elements.map((element) => ({ className: element.className, size: Math.round(element.getBoundingClientRect().height) })) + ); + expect(items.length, 'количество бейджей').toBe(6); + expect(items[0].size < items[1].size, 'base ниже lg').toBe(true); + expect(items[1].size < items[2].size, 'lg ниже xl').toBe(true); + expect(items[1].className, 'класс lg').toContain('p-badge-lg'); + expect(items[2].className, 'класс xl').toContain('p-badge-xl'); + } + }, + { + name: 'Dot: квадратные точки 8/12/16', + story: 'components-misc-badge--dot', + run: async ({ page, expect }) => { + const sizes = await page.locator('.p-badge-dot').evaluateAll((elements) => + elements.map((element) => { + const box = element.getBoundingClientRect(); + return { width: Math.round(box.width), height: Math.round(box.height) }; + }) + ); + expect(sizes.length, 'количество точек').toBeGreaterThanOrEqual(3); + for (const size of sizes) expect(size.width, 'точка квадратная').toBe(size.height); + expect(sizes[0].width < sizes.at(-1).width, 'есть увеличенные точки').toBe(true); + } + }, + { + name: 'Default: круглый бейдж с числом', + story: 'components-misc-badge--default', + run: async ({ page, expect }) => { + const badge = page.locator('.p-badge').first(); + expect(await badge.innerText(), 'текст бейджа').toBe('8'); + expect(await badge.getAttribute('class'), 'круглая форма').toContain('p-badge-circle'); + } + }, + ...STORIES.map(smoke), + { ...smoke(STORIES[0]), name: `Smoke: ${STORIES[0].name} (тёмная тема)`, theme: 'dark' } + ] +}; diff --git a/e2e/specs/breadcrumb.e2e.mjs b/e2e/specs/breadcrumb.e2e.mjs new file mode 100644 index 00000000..3483ff19 --- /dev/null +++ b/e2e/specs/breadcrumb.e2e.mjs @@ -0,0 +1,49 @@ +/** + * E2E-спека Breadcrumb: элементы, ссылки и режим только с иконками. + */ + +const STORIES = [ + { id: 'components-menu-breadcrumb--basic', name: 'Basic' }, + { id: 'components-menu-breadcrumb--default', name: 'Default' }, + { id: 'components-menu-breadcrumb--icons-only', name: 'IconsOnly' } +]; + +const smoke = (story) => ({ + name: `Smoke: ${story.name}`, + story: story.id, + run: async ({ page, expect, errors }) => { + expect(errors.filter((error) => error.type === 'pageerror').map((error) => error.text), 'ошибки страницы').toEqual([]); + expect(await page.locator('#storybook-root > *').count(), 'корень story').toBeGreaterThan(0); + const box = await page.locator('#storybook-root').boundingBox(); + expect(Boolean(box && box.width > 0), 'ширина story').toBe(true); + } +}); + +export default { + component: 'breadcrumb', + stories: Object.fromEntries(STORIES.map((story) => [story.id, story.id])), + tests: [ + { + name: 'Default: три элемента и ссылки', + story: 'components-menu-breadcrumb--default', + run: async ({ page, expect }) => { + expect(await page.locator('.p-breadcrumb-item').count(), 'элементы').toBe(3); + const texts = await page.locator('.p-breadcrumb-item-link').evaluateAll((links) => links.map((link) => link.textContent.trim())); + expect(texts.filter(Boolean), 'тексты').toEqual(['Электроника', 'Компьютеры', 'Ноутбуки']); + expect(await page.locator('.p-breadcrumb a.p-breadcrumb-item-link').count(), 'ссылки').toBeGreaterThanOrEqual(2); + } + }, + { + name: 'IconsOnly: три элемента без текста', + story: 'components-menu-breadcrumb--icons-only', + run: async ({ page, expect }) => { + expect(await page.locator('.p-breadcrumb-item').count(), 'элементы').toBe(3); + const texts = await page.locator('.p-breadcrumb-item').evaluateAll((items) => items.map((item) => item.textContent.trim())); + expect(texts.every((text) => text === ''), 'текста нет').toBe(true); + expect(await page.locator('.p-breadcrumb .ti').count(), 'иконки').toBeGreaterThanOrEqual(3); + } + }, + ...STORIES.map(smoke), + { ...smoke(STORIES[0]), name: `Smoke: ${STORIES[0].name} (тёмная тема)`, theme: 'dark' } + ] +}; diff --git a/e2e/specs/button.e2e.mjs b/e2e/specs/button.e2e.mjs new file mode 100644 index 00000000..6c744a4c --- /dev/null +++ b/e2e/specs/button.e2e.mjs @@ -0,0 +1,47 @@ +/** + * Smoke-спека «button»: все story рендерятся без pageerror, тёмная тема. + * + * Сгенерировано e2e/generate-specs.mjs: глубокие сценарии (клавиатура, оверлеи, состояния) добавляются вручную. + */ + +const STORIES = [ + { id: "components-button--badge", name: "Badge" }, + { id: "components-button--default", name: "Default" }, + { id: "components-button--events", name: "Events" }, + { id: "components-button--fluid", name: "Fluid" }, + { id: "components-button--icons", name: "Icons" }, + { id: "components-button--rounded", name: "Rounded" }, + { id: "components-button--sizes", name: "Sizes" }, + { id: "components-button--states", name: "States" }, + { id: "components-button--variants", name: "Variants" }, +]; + +export default { + component: "button", + stories: Object.fromEntries(STORIES.map((story, index) => [`story-${index}`, story.id])), + tests: [ + ...STORIES.map((story, index) => ({ + name: `Smoke: ${story.name}`, + story: `story-${index}`, + run: async ({ page, expect, errors }) => { + const pageErrors = errors.filter((error) => error.type === 'pageerror'); + expect(pageErrors.map((error) => error.text), 'ошибки страницы').toEqual([]); + expect(await page.locator('#storybook-root > *').count(), 'корень story').toBeGreaterThan(0); + const box = await page.locator('#storybook-root').boundingBox(); + expect(Boolean(box && box.width > 0), 'ширина story').toBe(true); + } + })), + { + name: `Тёмная тема: ${STORIES[0].name}`, + story: 'story-0', + theme: 'dark', + run: async ({ page, expect, errors }) => { + const pageErrors = errors.filter((error) => error.type === 'pageerror'); + expect(pageErrors.map((error) => error.text), 'ошибки страницы').toEqual([]); + expect(await page.locator('#storybook-root > *').count(), 'корень story').toBeGreaterThan(0); + const box = await page.locator('#storybook-root').boundingBox(); + expect(Boolean(box && box.width > 0), 'ширина story').toBe(true); + } + } + ] +}; diff --git a/e2e/specs/card.e2e.mjs b/e2e/specs/card.e2e.mjs new file mode 100644 index 00000000..1dffea74 --- /dev/null +++ b/e2e/specs/card.e2e.mjs @@ -0,0 +1,86 @@ +/** + * E2E-спека Card: состав слотов, отсутствие шапки/футера/подзаголовка и тень. + */ + +const STORIES = [ + { id: 'components-panel-card--default', name: 'Default' }, + { id: 'components-panel-card--minimal', name: 'Minimal' }, + { id: 'components-panel-card--overlay', name: 'Overlay' }, + { id: 'components-panel-card--without-footer', name: 'WithoutFooter' }, + { id: 'components-panel-card--without-header', name: 'WithoutHeader' }, + { id: 'components-panel-card--without-subtitle', name: 'WithoutSubtitle' } +]; + +const smoke = (story) => ({ + name: `Smoke: ${story.name}`, + story: story.id, + run: async ({ page, expect, errors }) => { + expect(errors.filter((error) => error.type === 'pageerror').map((error) => error.text), 'ошибки страницы').toEqual([]); + expect(await page.locator('#storybook-root > *').count(), 'корень story').toBeGreaterThan(0); + const box = await page.locator('#storybook-root').boundingBox(); + expect(Boolean(box && box.width > 0), 'ширина story').toBe(true); + } +}); + +const count = (page, selector) => page.locator(selector).count(); + +export default { + component: 'card', + stories: Object.fromEntries(STORIES.map((story) => [story.id, story.id])), + tests: [ + { + name: 'Default: заголовок, подзаголовок, шапка, футер и alt изображения', + story: 'components-panel-card--default', + run: async ({ page, expect }) => { + expect(await page.locator('.p-card-title').innerText(), 'заголовок').toBe('Заголовок'); + expect(await page.locator('.p-card-subtitle').innerText(), 'подзаголовок').toBe('Подзаголовок'); + expect(await count(page, '.p-card-header'), 'шапка').toBe(1); + expect(await count(page, '.p-card-footer'), 'футер').toBe(1); + expect(await page.locator('.p-card img').getAttribute('alt'), 'alt изображения').toBe('Заголовок'); + } + }, + { + name: 'Minimal: только тело без заголовка и футера', + story: 'components-panel-card--minimal', + run: async ({ page, expect }) => { + expect(await count(page, '.p-card'), 'карточка').toBe(1); + expect(await count(page, '.p-card-title'), 'заголовок').toBe(0); + expect(await count(page, '.p-card-footer'), 'футер').toBe(0); + expect(await count(page, '.p-card-header'), 'шапка').toBe(0); + } + }, + { + name: 'Overlay: тень shadow-md', + story: 'components-panel-card--overlay', + run: async ({ page, expect }) => { + expect(await page.locator('.p-card').getAttribute('class'), 'класс тени').toContain('shadow-md'); + } + }, + { + name: 'WithoutHeader: нет шапки, но заголовок остался', + story: 'components-panel-card--without-header', + run: async ({ page, expect }) => { + expect(await count(page, '.p-card-header'), 'шапка').toBe(0); + expect(await page.locator('.p-card-title').innerText(), 'заголовок').toBe('Заголовок'); + } + }, + { + name: 'WithoutFooter и WithoutSubtitle: слоты отсутствуют', + story: 'components-panel-card--without-footer', + run: async ({ page, expect }) => { + expect(await count(page, '.p-card-footer'), 'футер').toBe(0); + expect(await count(page, '.p-card-title'), 'заголовок').toBe(1); + } + }, + { + name: 'WithoutSubtitle: подзаголовка нет', + story: 'components-panel-card--without-subtitle', + run: async ({ page, expect }) => { + expect(await count(page, '.p-card-subtitle'), 'подзаголовок').toBe(0); + expect(await page.locator('.p-card-title').innerText(), 'заголовок').toBe('Заголовок'); + } + }, + ...STORIES.map(smoke), + { ...smoke(STORIES[0]), name: `Smoke: ${STORIES[0].name} (тёмная тема)`, theme: 'dark' } + ] +}; diff --git a/e2e/specs/carousel.e2e.mjs b/e2e/specs/carousel.e2e.mjs new file mode 100644 index 00000000..75c2d881 --- /dev/null +++ b/e2e/specs/carousel.e2e.mjs @@ -0,0 +1,71 @@ +/** + * E2E-спека Carousel: слайды, индикаторы, ориентация и доступность навигации. + */ + +const STORIES = [ + { id: 'components-media-carousel--autoplay', name: 'Autoplay' }, + { id: 'components-media-carousel--default', name: 'Default' }, + { id: 'components-media-carousel--header-and-footer', name: 'Header And Footer' }, + { id: 'components-media-carousel--vertical', name: 'Vertical' } +]; + +const smoke = (story) => ({ + name: `Smoke: ${story.name}`, + story: story.id, + run: async ({ page, expect, errors }) => { + expect(errors.filter((error) => error.type === 'pageerror').map((error) => error.text), 'ошибки страницы').toEqual([]); + expect(await page.locator('#storybook-root > *').count(), 'корень story').toBeGreaterThan(0); + const box = await page.locator('#storybook-root').boundingBox(); + expect(Boolean(box && box.width > 0), 'ширина story').toBe(true); + } +}); + +export default { + component: 'carousel', + stories: Object.fromEntries(STORIES.map((story) => [story.id, story.id])), + tests: [ + { + name: 'Default: регион, четыре индикатора и переключение', + story: 'components-media-carousel--default', + run: async ({ page, expect }) => { + expect(await page.locator('.p-carousel').getAttribute('role'), 'role').toBe('region'); + expect(await page.locator('.p-carousel-indicator').count(), 'индикаторы').toBe(4); + const activeIndex = () => + page.locator('.p-carousel-indicator').evaluateAll((indicators) => + indicators.findIndex((indicator) => indicator.classList.contains('p-carousel-indicator-active')) + ); + expect(await activeIndex(), 'первый слайд').toBe(0); + + await page.locator('.p-carousel button.p-button').nth(1).click(); + expect(await activeIndex(), 'после Next').toBe(1); + } + }, + { + name: 'Vertical: вертикальная ориентация', + story: 'components-media-carousel--vertical', + run: async ({ page, expect }) => { + expect(await page.locator('.p-carousel').getAttribute('class'), 'класс').toContain('p-carousel-vertical'); + } + }, + { + name: 'Autoplay: шесть индикаторов', + story: 'components-media-carousel--autoplay', + run: async ({ page, expect }) => { + expect(await page.locator('.p-carousel-indicator').count(), 'индикаторы').toBe(6); + } + }, + { + name: 'Навигация: у кнопок есть доступные имена', + story: 'components-media-carousel--default', + knownIssue: 'Кнопки вперёд/назад — иконки без aria-label: скринридер не различает их', + run: async ({ page, expect }) => { + const names = await page.locator('.p-carousel button.p-button').evaluateAll((buttons) => + buttons.map((button) => button.getAttribute('aria-label') || button.textContent.trim()) + ); + expect(names.every(Boolean), 'имена кнопок').toBe(true); + } + }, + ...STORIES.map(smoke), + { ...smoke(STORIES[0]), name: `Smoke: ${STORIES[0].name} (тёмная тема)`, theme: 'dark' } + ] +}; diff --git a/e2e/specs/checkbox.e2e.mjs b/e2e/specs/checkbox.e2e.mjs new file mode 100644 index 00000000..b63e3877 --- /dev/null +++ b/e2e/specs/checkbox.e2e.mjs @@ -0,0 +1,89 @@ +/** + * E2E-спека Checkbox: переключение, indeterminate, состояния и клавиатура. + */ + +const STORIES = [ + { id: 'components-form-checkbox--default', name: 'Default' }, + { id: 'components-form-checkbox--indeterminate', name: 'Indeterminate' }, + { id: 'components-form-checkbox--labels', name: 'Labels' }, + { id: 'components-form-checkbox--states', name: 'States' } +]; + +const smoke = (story) => ({ + name: `Smoke: ${story.name}`, + story: story.id, + run: async ({ page, expect, errors }) => { + expect(errors.filter((error) => error.type === 'pageerror').map((error) => error.text), 'ошибки страницы').toEqual([]); + expect(await page.locator('#storybook-root > *').count(), 'корень story').toBeGreaterThan(0); + const box = await page.locator('#storybook-root').boundingBox(); + expect(Boolean(box && box.width > 0), 'ширина story').toBe(true); + } +}); + +export default { + component: 'checkbox', + stories: Object.fromEntries(STORIES.map((story) => [story.id, story.id])), + tests: [ + { + name: 'Default: клик переключает и ставит класс checked', + story: 'components-form-checkbox--default', + run: async ({ page, expect }) => { + const input = page.locator('.p-checkbox-input').first(); + expect(await input.isChecked(), 'до клика').toBe(false); + await page.locator('.p-checkbox').first().click(); + expect(await input.isChecked(), 'после клика').toBe(true); + expect(await page.locator('.p-checkbox').first().getAttribute('class'), 'класс').toContain('p-checkbox-checked'); + } + }, + { + name: 'Labels: клик по лейблу переключает чекбокс', + story: 'components-form-checkbox--labels', + run: async ({ page, expect }) => { + const label = page.locator('label.checkbox-label').first(); + const input = page.locator('.p-checkbox-input').first(); + expect(await label.getAttribute('for'), 'for').toBe(await input.getAttribute('id')); + await label.click(); + expect(await input.isChecked(), 'после клика по лейблу').toBe(true); + } + }, + { + name: 'Indeterminate: хост помечен, нативное состояние mixed', + story: 'components-form-checkbox--indeterminate', + knownIssue: 'PrimeNG рисует p-checkbox-indeterminate, но не выставляет input.indeterminate: скринридер видит unchecked', + run: async ({ page, expect }) => { + const host = page.locator('.p-checkbox').first(); + expect(await host.getAttribute('class'), 'класс indeterminate').toContain('p-checkbox-indeterminate'); + expect(await page.locator('.p-checkbox-input').first().evaluate((element) => element.indeterminate), 'input.indeterminate').toBe(true); + } + }, + { + name: 'States: disabled и invalid', + story: 'components-form-checkbox--states', + run: async ({ page, expect }) => { + expect(await page.locator('.p-checkbox-input').nth(1).isDisabled(), 'disabled').toBe(true); + expect(await page.locator('.p-checkbox').nth(2).getAttribute('class'), 'invalid').toContain('p-invalid'); + } + }, + { + name: 'Keyboard: Space переключает чекбокс', + story: 'components-form-checkbox--default', + run: async ({ page, expect }) => { + const input = page.locator('.p-checkbox-input').first(); + await input.focus(); + await page.keyboard.press('Space'); + expect(await input.isChecked(), 'после Space').toBe(true); + } + }, + { + name: 'Checkbox: tabindex не должен быть NaN', + story: 'components-form-checkbox--default', + knownIssue: 'PrimeNG выставляет tabindex="NaN" на нативный input (невалидное значение)', + run: async ({ page, expect }) => { + const tabindex = await page.locator('.p-checkbox-input').first().getAttribute('tabindex'); + expect(tabindex === null || /^-?\d+$/.test(tabindex), 'валидный tabindex').toBe(true); + } + }, + ...STORIES.map(smoke), + { ...smoke(STORIES[0]), name: `Smoke: ${STORIES[0].name} (тёмная тема)`, theme: 'dark' } + ] +}; diff --git a/e2e/specs/chip.e2e.mjs b/e2e/specs/chip.e2e.mjs new file mode 100644 index 00000000..d6be07fa --- /dev/null +++ b/e2e/specs/chip.e2e.mjs @@ -0,0 +1,70 @@ +/** + * E2E-спека Chip: состояния, удаление и иконки. + */ + +const STORIES = [ + { id: 'components-misc-chip--default', name: 'Default' }, + { id: 'components-misc-chip--disabled', name: 'Disabled' }, + { id: 'components-misc-chip--removable', name: 'Removable' }, + { id: 'components-misc-chip--removable-with-icon', name: 'Removable With Icon' }, + { id: 'components-misc-chip--with-icon', name: 'With Icon' } +]; + +const smoke = (story) => ({ + name: `Smoke: ${story.name}`, + story: story.id, + run: async ({ page, expect, errors }) => { + expect(errors.filter((error) => error.type === 'pageerror').map((error) => error.text), 'ошибки страницы').toEqual([]); + expect(await page.locator('#storybook-root > *').count(), 'корень story').toBeGreaterThan(0); + const box = await page.locator('#storybook-root').boundingBox(); + expect(Boolean(box && box.width > 0), 'ширина story').toBe(true); + } +}); + +export default { + component: 'chip', + stories: Object.fromEntries(STORIES.map((story) => [story.id, story.id])), + tests: [ + { + name: 'Default: текст и доступное имя', + story: 'components-misc-chip--default', + run: async ({ page, expect }) => { + const chip = page.locator('.p-chip').first(); + expect(await chip.innerText(), 'текст').toBe('В пути'); + expect(await chip.getAttribute('aria-label'), 'aria-label').toBe('В пути'); + } + }, + { + name: 'Disabled: класс p-disabled', + story: 'components-misc-chip--disabled', + run: async ({ page, expect }) => { + expect(await page.locator('.p-chip').getAttribute('class'), 'класс').toContain('p-disabled'); + } + }, + { + name: 'Removable: иконки удаления доступны и удаляют чип', + story: 'components-misc-chip--removable', + run: async ({ page, expect, wait }) => { + expect(await page.locator('.p-chip').count(), 'чипы').toBe(3); + const removeIcons = page.locator('.p-chip-remove-icon'); + expect(await removeIcons.count(), 'иконки удаления').toBe(3); + expect(await removeIcons.first().getAttribute('aria-label'), 'aria-label').toBe('Удалить'); + expect(await removeIcons.first().getAttribute('role'), 'role').toBe('button'); + expect(await removeIcons.first().getAttribute('tabindex'), 'tabindex').toBe('0'); + + await removeIcons.first().click(); + await wait(async () => (await page.locator('.p-chip').count()) === 2); + expect(await page.locator('.p-chip').count(), 'чипов после удаления').toBe(2); + } + }, + { + name: 'With Icon: иконка внутри чипа', + story: 'components-misc-chip--with-icon', + run: async ({ page, expect }) => { + expect(await page.locator('.p-chip .ti').count(), 'иконка').toBeGreaterThan(0); + } + }, + ...STORIES.map(smoke), + { ...smoke(STORIES[0]), name: `Smoke: ${STORIES[0].name} (тёмная тема)`, theme: 'dark' } + ] +}; diff --git a/e2e/specs/confirm-dialog.e2e.mjs b/e2e/specs/confirm-dialog.e2e.mjs new file mode 100644 index 00000000..6cfc9f7e --- /dev/null +++ b/e2e/specs/confirm-dialog.e2e.mjs @@ -0,0 +1,67 @@ +/** + * E2E-спека ConfirmDialog: открытие, семантика, подтверждение и отмена. + */ + +const STORIES = [ + { id: 'components-overlay-confirmdialog--confirm-dialog', name: 'Confirm Dialog' }, + { id: 'components-overlay-confirmdialog--severities-story', name: 'Severities Story' }, + { id: 'components-overlay-confirmdialog--sizes', name: 'Sizes' }, + { id: 'components-overlay-confirmdialog--templates', name: 'Templates' } +]; + +const smoke = (story) => ({ + name: `Smoke: ${story.name}`, + story: story.id, + run: async ({ page, expect, errors }) => { + expect(errors.filter((error) => error.type === 'pageerror').map((error) => error.text), 'ошибки страницы').toEqual([]); + expect(await page.locator('#storybook-root > *').count(), 'корень story').toBeGreaterThan(0); + const box = await page.locator('#storybook-root').boundingBox(); + expect(Boolean(box && box.width > 0), 'ширина story').toBe(true); + } +}); + +const openConfirm = async (page) => { + await page.locator('button', { hasText: 'Показать диалог' }).click(); + await page.waitForSelector('.p-confirmdialog', { state: 'visible' }); +}; + +export default { + component: 'confirm-dialog', + stories: Object.fromEntries(STORIES.map((story) => [story.id, story.id])), + tests: [ + { + name: 'Confirm Dialog: текст и кнопки подтверждения', + story: 'components-overlay-confirmdialog--confirm-dialog', + run: async ({ page, expect }) => { + await openConfirm(page); + const dialog = page.locator('.p-confirmdialog'); + expect(await dialog.getAttribute('role'), 'role').toBe('alertdialog'); + expect(await dialog.innerText(), 'текст').toContain('Вы уверены'); + expect(await dialog.locator('button', { hasText: 'Да' }).count(), 'кнопка Да').toBe(1); + expect(await dialog.locator('button', { hasText: 'Нет' }).count(), 'кнопка Нет').toBe(1); + } + }, + { + name: 'Confirm Dialog: Да закрывает диалог', + story: 'components-overlay-confirmdialog--confirm-dialog', + run: async ({ page, expect }) => { + await openConfirm(page); + await page.locator('.p-confirmdialog button', { hasText: 'Да' }).click(); + await page.waitForSelector('.p-confirmdialog', { state: 'detached' }); + expect(await page.locator('.p-confirmdialog').count(), 'после Да').toBe(0); + } + }, + { + name: 'Confirm Dialog: Нет закрывает диалог', + story: 'components-overlay-confirmdialog--confirm-dialog', + run: async ({ page, expect }) => { + await openConfirm(page); + await page.locator('.p-confirmdialog button', { hasText: 'Нет' }).click(); + await page.waitForSelector('.p-confirmdialog', { state: 'detached' }); + expect(await page.locator('.p-confirmdialog').count(), 'после Нет').toBe(0); + } + }, + ...STORIES.map(smoke), + { ...smoke(STORIES[0]), name: `Smoke: ${STORIES[0].name} (тёмная тема)`, theme: 'dark' } + ] +}; diff --git a/e2e/specs/date-picker.e2e.mjs b/e2e/specs/date-picker.e2e.mjs new file mode 100644 index 00000000..9928bd53 --- /dev/null +++ b/e2e/specs/date-picker.e2e.mjs @@ -0,0 +1,131 @@ +/** + * E2E-спека DatePicker: календарь, выбор даты, диапазон, inline и состояния. + */ + +const STORIES = [ + { id: 'components-form-datepicker--button-bar', name: 'Button Bar' }, + { id: 'components-form-datepicker--clear-icon', name: 'Clear Icon' }, + { id: 'components-form-datepicker--default', name: 'Default' }, + { id: 'components-form-datepicker--disabled', name: 'Disabled' }, + { id: 'components-form-datepicker--inline', name: 'Inline' }, + { id: 'components-form-datepicker--invalid', name: 'Invalid' }, + { id: 'components-form-datepicker--locale', name: 'Locale' }, + { id: 'components-form-datepicker--range', name: 'Range' }, + { id: 'components-form-datepicker--time', name: 'Time' } +]; + +const smoke = (story) => ({ + name: `Smoke: ${story.name}`, + story: story.id, + run: async ({ page, expect, errors }) => { + expect(errors.filter((error) => error.type === 'pageerror').map((error) => error.text), 'ошибки страницы').toEqual([]); + expect(await page.locator('#storybook-root > *').count(), 'корень story').toBeGreaterThan(0); + const box = await page.locator('#storybook-root').boundingBox(); + expect(Boolean(box && box.width > 0), 'ширина story').toBe(true); + } +}); + +const openPicker = async (page) => { + await page.locator('input.p-datepicker-input').click(); + await page.waitForSelector('.p-datepicker-panel', { state: 'visible' }); +}; + +const pickDay = async (page, index = 3) => { + const days = page.locator('.p-datepicker-panel td:not(.p-datepicker-other-month) span:not(.p-disabled)'); + await days.nth(index).click(); +}; + +export default { + component: 'date-picker', + stories: Object.fromEntries(STORIES.map((story) => [story.id, story.id])), + tests: [ + { + name: 'Default: диалог календаря и выбор даты', + story: 'components-form-datepicker--default', + run: async ({ page, expect }) => { + const input = page.locator('input.p-datepicker-input'); + expect(await input.getAttribute('role'), 'role поля').toBe('combobox'); + expect(await input.getAttribute('aria-expanded'), 'до открытия').toBe('false'); + + await openPicker(page); + const panel = page.locator('.p-datepicker-panel'); + expect(await panel.getAttribute('role'), 'role календаря').toBe('dialog'); + expect(await panel.getAttribute('aria-label'), 'имя календаря').toBe('Выбрать дату'); + expect(await page.locator('.p-datepicker-panel td').count(), 'ячейки').toBe(42); + + await pickDay(page); + expect(await input.inputValue(), 'значение').toMatch(/^\d{2}\.\d{2}\.\d{4}$/); + } + }, + { + name: 'Default: панель закрывается после выбора даты', + story: 'components-form-datepicker--default', + knownIssue: 'После выбора даты панель остаётся открытой: aria-expanded не сбрасывается', + run: async ({ page, expect, wait }) => { + const input = page.locator('input.p-datepicker-input'); + await openPicker(page); + await pickDay(page); + await wait(async () => (await input.getAttribute('aria-expanded')) === 'false', { timeout: 2000 }); + expect(await input.getAttribute('aria-expanded'), 'aria-expanded').toBe('false'); + } + }, + { + name: 'Clear Icon: иконка очищает выбранную дату', + story: 'components-form-datepicker--clear-icon', + run: async ({ page, expect }) => { + const input = page.locator('input.p-datepicker-input'); + await openPicker(page); + await pickDay(page); + expect(await page.locator('.p-datepicker-clear-icon').count(), 'иконка очистки').toBe(1); + + await page.locator('.p-datepicker-clear-icon').click(); + expect(await input.inputValue(), 'значение после очистки').toBe(''); + } + }, + { + name: 'Range: выбор двух дат даёт период', + story: 'components-form-datepicker--range', + run: async ({ page, expect }) => { + const input = page.locator('input.p-datepicker-input'); + await openPicker(page); + await pickDay(page, 2); + await pickDay(page, 6); + expect(await input.inputValue(), 'период').toMatch(/^\d{2}\.\d{2}\.\d{4} - \d{2}\.\d{2}\.\d{4}$/); + } + }, + { + name: 'Inline: календарь виден без поля', + story: 'components-form-datepicker--inline', + run: async ({ page, expect }) => { + expect(await page.locator('input.p-datepicker-input').count(), 'поле ввода').toBe(0); + expect(await page.locator('.p-datepicker-panel').isVisible(), 'календарь').toBe(true); + expect(await page.locator('.p-datepicker-panel td').count(), 'ячейки').toBe(42); + } + }, + { + name: 'Disabled: поле отключено', + story: 'components-form-datepicker--disabled', + knownIssue: 'FormControl.disable() не доходит до input: disabled=false, класс p-disabled отсутствует', + run: async ({ page, expect }) => { + expect(await page.locator('input.p-datepicker-input').isDisabled(), 'disabled').toBe(true); + } + }, + { + name: 'Invalid: поле объявляет aria-invalid', + story: 'components-form-datepicker--invalid', + knownIssue: 'PrimeNG ставит только класс p-invalid; aria-invalid отсутствует', + run: async ({ page, expect }) => { + expect(await page.locator('input.p-datepicker-input').getAttribute('aria-invalid'), 'aria-invalid').toBe('true'); + } + }, + { + name: 'Locale: английские названия месяцев', + story: 'components-form-datepicker--locale', + run: async ({ page, expect }) => { + expect(await page.locator('.p-datepicker-panel').innerText(), 'календарь').toContain('November'); + } + }, + ...STORIES.map(smoke), + { ...smoke(STORIES[0]), name: `Smoke: ${STORIES[0].name} (тёмная тема)`, theme: 'dark' } + ] +}; diff --git a/e2e/specs/dialog.e2e.mjs b/e2e/specs/dialog.e2e.mjs new file mode 100644 index 00000000..389bebd5 --- /dev/null +++ b/e2e/specs/dialog.e2e.mjs @@ -0,0 +1,89 @@ +/** + * E2E-спека Dialog: открытие, семантика, размеры, фичи и закрытие. + */ + +const STORIES = [ + { id: 'components-overlay-dialog--basic', name: 'Basic' }, + { id: 'components-overlay-dialog--dynamic', name: 'Dynamic' }, + { id: 'components-overlay-dialog--features', name: 'Features' }, + { id: 'components-overlay-dialog--header', name: 'Header' }, + { id: 'components-overlay-dialog--sizes', name: 'Sizes' }, + { id: 'components-overlay-dialog--slots', name: 'Slots' } +]; + +const smoke = (story) => ({ + name: `Smoke: ${story.name}`, + story: story.id, + run: async ({ page, expect, errors }) => { + expect(errors.filter((error) => error.type === 'pageerror').map((error) => error.text), 'ошибки страницы').toEqual([]); + expect(await page.locator('#storybook-root > *').count(), 'корень story').toBeGreaterThan(0); + const box = await page.locator('#storybook-root').boundingBox(); + expect(Boolean(box && box.width > 0), 'ширина story').toBe(true); + } +}); + +const openBasic = async (page) => { + await page.locator('button', { hasText: 'Открыть окно' }).first().click(); + await page.waitForSelector('.p-dialog', { state: 'visible' }); +}; + +export default { + component: 'dialog', + stories: Object.fromEntries(STORIES.map((story) => [story.id, story.id])), + tests: [ + { + name: 'Basic: диалог, заголовок и aria-modal', + story: 'components-overlay-dialog--basic', + run: async ({ page, expect }) => { + await openBasic(page); + const dialog = page.locator('[role=dialog]'); + expect(await dialog.count(), 'диалог').toBe(1); + expect(await dialog.getAttribute('aria-modal'), 'aria-modal').toBe('true'); + expect(await dialog.getAttribute('aria-labelledby'), 'aria-labelledby').toBeTruthy(); + expect(await page.locator('.p-dialog-title').innerText(), 'заголовок').toBe('Подтверждение заявки'); + } + }, + { + name: 'Basic: Esc закрывает диалог', + story: 'components-overlay-dialog--basic', + run: async ({ page, expect }) => { + await openBasic(page); + await page.keyboard.press('Escape'); + await page.waitForSelector('.p-dialog', { state: 'detached' }); + expect(await page.locator('.p-dialog').count(), 'после Esc').toBe(0); + } + }, + { + name: 'Sizes: кнопка SM открывает компактный диалог', + story: 'components-overlay-dialog--sizes', + run: async ({ page, expect }) => { + await page.locator('button', { hasText: 'SM' }).first().click({ force: true }); + await page.locator('button', { hasText: 'Открыть окно (sm)' }).click({ force: true }); + await page.waitForSelector('.p-dialog', { state: 'visible' }); + const className = await page.locator('.p-dialog').getAttribute('class'); + expect(className.includes('p-dialog-sm') || (await page.locator('.p-dialog').boundingBox()).width < 500, 'компактный').toBe(true); + } + }, + { + name: 'Features: без showClose нет кнопки закрытия', + story: 'components-overlay-dialog--features', + run: async ({ page, expect }) => { + await page.locator('button', { hasText: 'Без закрытия' }).click(); + await page.waitForSelector('.p-dialog', { state: 'visible' }); + expect(await page.locator('.p-dialog-close-button').count(), 'кнопка закрытия').toBe(0); + } + }, + { + name: 'Фокус после открытия остаётся внутри диалога', + story: 'components-overlay-dialog--basic', + knownIssue: 'После открытия фокус остаётся на документе, а не внутри диалога', + run: async ({ page, expect }) => { + await openBasic(page); + const inside = await page.evaluate(() => Boolean(document.activeElement?.closest('.p-dialog'))); + expect(inside, 'фокус в диалоге').toBe(true); + } + }, + ...STORIES.map(smoke), + { ...smoke(STORIES[0]), name: `Smoke: ${STORIES[0].name} (тёмная тема)`, theme: 'dark' } + ] +}; diff --git a/e2e/specs/divider.e2e.mjs b/e2e/specs/divider.e2e.mjs new file mode 100644 index 00000000..b4071bd1 --- /dev/null +++ b/e2e/specs/divider.e2e.mjs @@ -0,0 +1,71 @@ +/** + * E2E-спека Divider: ориентация, тип линии, контент и иконка. + */ + +const STORIES = [ + { id: 'components-panel-divider--align-bottom', name: 'Align Bottom' }, + { id: 'components-panel-divider--align-left', name: 'Align Left' }, + { id: 'components-panel-divider--type-dashed', name: 'Dashed' }, + { id: 'components-panel-divider--default', name: 'Default' }, + { id: 'components-panel-divider--vertical', name: 'Vertical' }, + { id: 'components-panel-divider--with-content', name: 'With Content' }, + { id: 'components-panel-divider--with-icon', name: 'With Icon' } +]; + +const smoke = (story) => ({ + name: `Smoke: ${story.name}`, + story: story.id, + run: async ({ page, expect, errors }) => { + expect(errors.filter((error) => error.type === 'pageerror').map((error) => error.text), 'ошибки страницы').toEqual([]); + expect(await page.locator('#storybook-root > *').count(), 'корень story').toBeGreaterThan(0); + const box = await page.locator('#storybook-root').boundingBox(); + expect(Boolean(box && box.width > 0), 'ширина story').toBe(true); + } +}); + +export default { + component: 'divider', + stories: Object.fromEntries(STORIES.map((story) => [story.id, story.id])), + tests: [ + { + name: 'Default: separator, горизонтальный и контент', + story: 'components-panel-divider--default', + run: async ({ page, expect }) => { + const divider = page.locator('.p-divider'); + expect(await divider.getAttribute('role'), 'role').toBe('separator'); + expect(await divider.getAttribute('class'), 'горизонтальный').toContain('p-divider-horizontal'); + expect((await divider.evaluate((element) => element.textContent)).trim(), 'контент').toBe('Отправитель'); + } + }, + { + name: 'Dashed: класс p-divider-dashed', + story: 'components-panel-divider--type-dashed', + run: async ({ page, expect }) => { + expect(await page.locator('.p-divider').getAttribute('class'), 'пунктир').toContain('p-divider-dashed'); + } + }, + { + name: 'Vertical: вертикальная ориентация', + story: 'components-panel-divider--vertical', + run: async ({ page, expect }) => { + expect(await page.locator('.p-divider').getAttribute('class'), 'вертикальный').toContain('p-divider-vertical'); + } + }, + { + name: 'With Content: текст внутри разделителя', + story: 'components-panel-divider--with-content', + run: async ({ page, expect }) => { + expect((await page.locator('.p-divider-content').evaluate((element) => element.textContent)).trim(), 'контент').toBe('Москва → Новосибирск'); + } + }, + { + name: 'With Icon: иконка внутри разделителя', + story: 'components-panel-divider--with-icon', + run: async ({ page, expect }) => { + expect(await page.locator('.p-divider-content .ti-map-pin').count(), 'иконка').toBe(1); + } + }, + ...STORIES.map(smoke), + { ...smoke(STORIES[0]), name: `Smoke: ${STORIES[0].name} (тёмная тема)`, theme: 'dark' } + ] +}; diff --git a/e2e/specs/drawer.e2e.mjs b/e2e/specs/drawer.e2e.mjs new file mode 100644 index 00000000..729016df --- /dev/null +++ b/e2e/specs/drawer.e2e.mjs @@ -0,0 +1,71 @@ +/** + * E2E-спека Drawer: открытие, позиции, размеры и закрытие. + */ + +const STORIES = [ + { id: 'components-overlay-drawer--default', name: 'Default' }, + { id: 'components-overlay-drawer--full-screen', name: 'Full Screen' }, + { id: 'components-overlay-drawer--position', name: 'Position' }, + { id: 'components-overlay-drawer--sizes', name: 'Sizes' }, + { id: 'components-overlay-drawer--with-custom-header', name: 'With Custom Header' }, + { id: 'components-overlay-drawer--with-footer', name: 'With Footer' }, + { id: 'components-overlay-drawer--without-modal', name: 'Without Modal' } +]; + +const smoke = (story) => ({ + name: `Smoke: ${story.name}`, + story: story.id, + run: async ({ page, expect, errors }) => { + expect(errors.filter((error) => error.type === 'pageerror').map((error) => error.text), 'ошибки страницы').toEqual([]); + expect(await page.locator('#storybook-root > *').count(), 'корень story').toBeGreaterThan(0); + const box = await page.locator('#storybook-root').boundingBox(); + expect(Boolean(box && box.width > 0), 'ширина story').toBe(true); + } +}); + +const openDrawer = async (page) => { + await page.locator('button', { hasText: 'Open Drawer' }).click(); + await page.waitForSelector('.p-drawer', { state: 'visible' }); +}; + +export default { + component: 'drawer', + stories: Object.fromEntries(STORIES.map((story) => [story.id, story.id])), + tests: [ + { + name: 'Default: панель открывается и закрывается по Esc', + story: 'components-overlay-drawer--default', + run: async ({ page, expect }) => { + await openDrawer(page); + expect(await page.locator('.p-drawer').count(), 'панель').toBe(1); + await page.keyboard.press('Escape'); + await page.waitForSelector('.p-drawer', { state: 'detached' }); + expect(await page.locator('.p-drawer').count(), 'после Esc').toBe(0); + } + }, + { + name: 'Position: Left открывает панель слева', + story: 'components-overlay-drawer--position', + run: async ({ page, expect }) => { + await page.locator('button', { hasText: 'Left' }).click(); + await page.waitForSelector('.p-drawer', { state: 'visible' }); + expect(await page.locator('.p-drawer').getAttribute('class'), 'класс').toContain('p-drawer-left'); + } + }, + { + name: 'Drawer: панель объявляет роль и имя', + story: 'components-overlay-drawer--default', + knownIssue: 'p-drawer имеет role=complementary без aria-modal/aria-label: диалоговая панель не объявляется как диалог', + run: async ({ page, expect }) => { + await openDrawer(page); + const drawer = page.locator('.p-drawer'); + const role = await drawer.getAttribute('role'); + const modal = await drawer.getAttribute('aria-modal'); + const label = await drawer.getAttribute('aria-label') || (await drawer.getAttribute('aria-labelledby')); + expect(role === 'dialog' && modal === 'true' && Boolean(label), 'семантика диалога').toBe(true); + } + }, + ...STORIES.map(smoke), + { ...smoke(STORIES[0]), name: `Smoke: ${STORIES[0].name} (тёмная тема)`, theme: 'dark' } + ] +}; diff --git a/e2e/specs/fileupload.e2e.mjs b/e2e/specs/fileupload.e2e.mjs new file mode 100644 index 00000000..c0c052f5 --- /dev/null +++ b/e2e/specs/fileupload.e2e.mjs @@ -0,0 +1,67 @@ +/** + * E2E-спека FileUpload: поле выбора файла, загрузка и режимы. + */ + +import { writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; + +const STORIES = [ + { id: 'components-form-fileupload--auto', name: 'Auto upload' }, + { id: 'components-form-fileupload--basic', name: 'Basic' }, + { id: 'components-form-fileupload--default', name: 'Default' }, + { id: 'components-form-fileupload--with-form', name: 'Reactive Form' }, + { id: 'components-form-fileupload--upload-error', name: 'Upload error' }, + { id: 'components-form-fileupload--without-drag-and-drop', name: 'Without drag-and-drop' } +]; + +const smoke = (story) => ({ + name: `Smoke: ${story.name}`, + story: story.id, + run: async ({ page, expect, errors }) => { + expect(errors.filter((error) => error.type === 'pageerror').map((error) => error.text), 'ошибки страницы').toEqual([]); + expect(await page.locator('#storybook-root > *').count(), 'корень story').toBeGreaterThan(0); + const box = await page.locator('#storybook-root').boundingBox(); + expect(Boolean(box && box.width > 0), 'ширина story').toBe(true); + } +}); + +const sampleFile = () => { + const file = join(tmpdir(), 'e2e-upload.txt'); + writeFileSync(file, 'e2e upload'); + return file; +}; + +export default { + component: 'fileupload', + stories: Object.fromEntries(STORIES.map((story) => [story.id, story.id])), + tests: [ + { + name: 'Basic: поле выбора файла и кнопка', + story: 'components-form-fileupload--basic', + run: async ({ page, expect }) => { + expect(await page.locator('input[type=file]').count(), 'поле файла').toBe(1); + expect(await page.locator('button', { hasText: 'Выбрать файл' }).count(), 'кнопка').toBe(1); + } + }, + { + name: 'Basic: выбранный файл появляется в списке', + story: 'components-form-fileupload--basic', + knownIssue: 'После выбора файла список не обновляется: .p-fileupload-file-list остаётся пустым', + run: async ({ page, expect, wait }) => { + await page.locator('input[type=file]').setInputFiles(sampleFile()); + await wait(async () => (await page.locator('.p-fileupload-file-list .p-fileupload-file').count()) > 0, { timeout: 2000 }); + expect(await page.locator('.p-fileupload-file').count(), 'файлы').toBeGreaterThan(0); + } + }, + { + name: 'Without drag-and-drop: нет зоны перетаскивания', + story: 'components-form-fileupload--without-drag-and-drop', + run: async ({ page, expect }) => { + expect(await page.locator('.p-fileupload-dragdrop').count(), 'drag-and-drop').toBe(0); + } + }, + ...STORIES.map(smoke), + { ...smoke(STORIES[0]), name: `Smoke: ${STORIES[0].name} (тёмная тема)`, theme: 'dark' } + ] +}; diff --git a/e2e/specs/galleria.e2e.mjs b/e2e/specs/galleria.e2e.mjs new file mode 100644 index 00000000..3775b28a --- /dev/null +++ b/e2e/specs/galleria.e2e.mjs @@ -0,0 +1,81 @@ +/** + * E2E-спека Galleria: индикаторы, миниатюры, подписи и навигация. + */ + +const STORIES = [ + { id: 'components-media-galleria--autoplay', name: 'Autoplay' }, + { id: 'components-media-galleria--caption', name: 'Caption' }, + { id: 'components-media-galleria--default', name: 'Default' }, + { id: 'components-media-galleria--full-screen', name: 'FullScreen' }, + { id: 'components-media-galleria--indicator', name: 'Indicator' }, + { id: 'components-media-galleria--thumbnails', name: 'Thumbnails' } +]; + +const smoke = (story) => ({ + name: `Smoke: ${story.name}`, + story: story.id, + run: async ({ page, expect, errors }) => { + expect(errors.filter((error) => error.type === 'pageerror').map((error) => error.text), 'ошибки страницы').toEqual([]); + expect(await page.locator('#storybook-root > *').count(), 'корень story').toBeGreaterThan(0); + const box = await page.locator('#storybook-root').boundingBox(); + expect(Boolean(box && box.width > 0), 'ширина story').toBe(true); + } +}); + +export default { + component: 'galleria', + stories: Object.fromEntries(STORIES.map((story) => [story.id, story.id])), + tests: [ + { + name: 'Default: регион, индикаторы и активный слайд', + story: 'components-media-galleria--default', + run: async ({ page, expect }) => { + expect(await page.locator('.p-galleria').getAttribute('role'), 'role').toBe('region'); + expect(await page.locator('.p-galleria-indicator').count(), 'индикаторы').toBe(4); + expect(await page.locator('.p-galleria-item').first().getAttribute('aria-label'), 'подпись слайда').toBe('1'); + } + }, + { + name: 'Thumbnails: четыре миниатюры и переключение', + story: 'components-media-galleria--thumbnails', + run: async ({ page, expect }) => { + const thumbs = page.locator('.p-galleria-thumbnail-item'); + expect(await thumbs.count(), 'миниатюры').toBe(4); + expect(await page.locator('.p-galleria-thumbnail-item-current').count(), 'текущая').toBe(1); + + await thumbs.nth(1).click(); + expect(await thumbs.nth(1).getAttribute('class'), 'вторая текущая').toContain('p-galleria-thumbnail-item-current'); + } + }, + { + name: 'Caption: подпись слайда', + story: 'components-media-galleria--caption', + run: async ({ page, expect }) => { + expect(await page.locator('#storybook-root').innerText(), 'подпись').toContain('Доставка'); + } + }, + { + name: 'Indicator: заголовок и футер', + story: 'components-media-galleria--indicator', + run: async ({ page, expect }) => { + const text = await page.locator('#storybook-root').innerText(); + expect(text, 'заголовок').toContain('Галерея СДЭК'); + expect(text, 'подсказка').toContain('Переключайте изображения'); + } + }, + { + name: 'Навигация: у кнопок есть доступные имена', + story: 'components-media-galleria--default', + knownIssue: 'Кнопки p-galleria-prev/next без aria-label: скринридер не различает их', + run: async ({ page, expect }) => { + const names = await page.locator('.p-galleria-nav-button').evaluateAll((buttons) => + buttons.map((button) => button.getAttribute('aria-label') || button.textContent.trim()) + ); + expect(names.length, 'кнопки').toBeGreaterThan(0); + expect(names.every(Boolean), 'имена кнопок').toBe(true); + } + }, + ...STORIES.map(smoke), + { ...smoke(STORIES[0]), name: `Smoke: ${STORIES[0].name} (тёмная тема)`, theme: 'dark' } + ] +}; diff --git a/e2e/specs/inputgroup.e2e.mjs b/e2e/specs/inputgroup.e2e.mjs new file mode 100644 index 00000000..f2d6bc08 --- /dev/null +++ b/e2e/specs/inputgroup.e2e.mjs @@ -0,0 +1,72 @@ +/** + * E2E-спека InputGroup: аддоны, размеры и disabled. + */ + +const STORIES = [ + { id: 'components-form-inputgroup--addon-both', name: 'AddonBoth' }, + { id: 'components-form-inputgroup--addon-right', name: 'AddonRight' }, + { id: 'components-form-inputgroup--default', name: 'Default' }, + { id: 'components-form-inputgroup--disabled', name: 'Disabled' }, + { id: 'components-form-inputgroup--sizes', name: 'Sizes' }, + { id: 'components-form-inputgroup--with-text', name: 'WithText' } +]; + +const smoke = (story) => ({ + name: `Smoke: ${story.name}`, + story: story.id, + run: async ({ page, expect, errors }) => { + expect(errors.filter((error) => error.type === 'pageerror').map((error) => error.text), 'ошибки страницы').toEqual([]); + expect(await page.locator('#storybook-root > *').count(), 'корень story').toBeGreaterThan(0); + const box = await page.locator('#storybook-root').boundingBox(); + expect(Boolean(box && box.width > 0), 'ширина story').toBe(true); + } +}); + +export default { + component: 'inputgroup', + stories: Object.fromEntries(STORIES.map((story) => [story.id, story.id])), + tests: [ + { + name: 'Default: аддон слева и поле', + story: 'components-form-inputgroup--default', + run: async ({ page, expect }) => { + expect(await page.locator('.p-inputgroup').getAttribute('class'), 'аддон слева').toContain('extra-input-group--addon-left'); + expect(await page.locator('.p-inputgroupaddon').count(), 'аддон').toBe(1); + expect(await page.locator('.p-inputgroup input').count(), 'поле').toBe(1); + } + }, + { + name: 'AddonBoth: аддоны с двух сторон', + story: 'components-form-inputgroup--addon-both', + run: async ({ page, expect }) => { + expect(await page.locator('.p-inputgroup').getAttribute('class'), 'класс').toContain('extra-input-group--addon-both'); + expect(await page.locator('.p-inputgroup input').count(), 'поле').toBe(1); + } + }, + { + name: 'WithText: текстовый аддон @', + story: 'components-form-inputgroup--with-text', + run: async ({ page, expect }) => { + expect(await page.locator('.p-inputgroup').innerText(), 'текст аддона').toContain('@'); + } + }, + { + name: 'Sizes: xlarge высота 64', + story: 'components-form-inputgroup--sizes', + run: async ({ page, expect }) => { + const box = await page.locator('.p-inputgroup input').boundingBox(); + expect(Math.round(box.height), 'высота').toBe(64); + expect(await page.locator('input').getAttribute('class'), 'класс xlg').toContain('p-inputtext-xlg'); + } + }, + { + name: 'Disabled: поле отключено', + story: 'components-form-inputgroup--disabled', + run: async ({ page, expect }) => { + expect(await page.locator('.p-inputgroup input').isDisabled(), 'disabled').toBe(true); + } + }, + ...STORIES.map(smoke), + { ...smoke(STORIES[0]), name: `Smoke: ${STORIES[0].name} (тёмная тема)`, theme: 'dark' } + ] +}; diff --git a/e2e/specs/inputmask.e2e.mjs b/e2e/specs/inputmask.e2e.mjs new file mode 100644 index 00000000..6aaf5bfe --- /dev/null +++ b/e2e/specs/inputmask.e2e.mjs @@ -0,0 +1,78 @@ +/** + * E2E-спека InputMask: маска, очистка, состояния и лейблы. + */ + +const STORIES = [ + { id: 'components-form-inputmask--clearable', name: 'Clearable' }, + { id: 'components-form-inputmask--default', name: 'Default' }, + { id: 'components-form-inputmask--fluid', name: 'Fluid' }, + { id: 'components-form-inputmask--labels', name: 'Labels' }, + { id: 'components-form-inputmask--reactive-forms', name: 'ReactiveForms' }, + { id: 'components-form-inputmask--sizes', name: 'Sizes' }, + { id: 'components-form-inputmask--states', name: 'States' } +]; + +const smoke = (story) => ({ + name: `Smoke: ${story.name}`, + story: story.id, + run: async ({ page, expect, errors }) => { + expect(errors.filter((error) => error.type === 'pageerror').map((error) => error.text), 'ошибки страницы').toEqual([]); + expect(await page.locator('#storybook-root > *').count(), 'корень story').toBeGreaterThan(0); + const box = await page.locator('#storybook-root').boundingBox(); + expect(Boolean(box && box.width > 0), 'ширина story').toBe(true); + } +}); + +export default { + component: 'inputmask', + stories: Object.fromEntries(STORIES.map((story) => [story.id, story.id])), + tests: [ + { + name: 'Default: маска телефона форматирует ввод', + story: 'components-form-inputmask--default', + run: async ({ page, expect }) => { + const input = page.locator('input').first(); + expect(await input.getAttribute('placeholder'), 'плейсхолдер маски').toBe('(___) ___-____'); + await input.fill('4951234567'); + expect(await input.inputValue(), 'отформатированное значение').toBe('(495) 123-4567'); + } + }, + { + name: 'Clearable: иконка очищает значение', + story: 'components-form-inputmask--clearable', + run: async ({ page, expect }) => { + const input = page.locator('input').first(); + expect(await page.locator('.p-inputmask-clear-icon').count(), 'иконка очистки').toBe(1); + await page.locator('.p-inputmask-clear-icon').click(); + expect(await input.inputValue(), 'значение после очистки').toBe(''); + } + }, + { + name: 'States: disabled, readonly и invalid', + story: 'components-form-inputmask--states', + run: async ({ page, expect }) => { + expect(await page.locator('input').nth(1).isDisabled(), 'disabled').toBe(true); + expect(await page.locator('input').nth(2).evaluate((element) => element.readOnly), 'readonly').toBe(true); + expect(await page.locator('input').nth(3).getAttribute('class'), 'invalid').toContain('p-invalid'); + } + }, + { + name: 'Labels: лейбл связан с полем', + story: 'components-form-inputmask--labels', + run: async ({ page, expect }) => { + const label = page.locator('label').first(); + expect(await label.getAttribute('for'), 'for').toBe(await page.locator('input').first().getAttribute('id')); + } + }, + { + name: 'Invalid: поле объявляет aria-invalid', + story: 'components-form-inputmask--states', + knownIssue: 'PrimeNG ставит только класс p-invalid; aria-invalid отсутствует', + run: async ({ page, expect }) => { + expect(await page.locator('input').nth(3).getAttribute('aria-invalid'), 'aria-invalid').toBe('true'); + } + }, + ...STORIES.map(smoke), + { ...smoke(STORIES[0]), name: `Smoke: ${STORIES[0].name} (тёмная тема)`, theme: 'dark' } + ] +}; diff --git a/e2e/specs/inputnumber.e2e.mjs b/e2e/specs/inputnumber.e2e.mjs new file mode 100644 index 00000000..97616c60 --- /dev/null +++ b/e2e/specs/inputnumber.e2e.mjs @@ -0,0 +1,77 @@ +/** + * E2E-спека InputNumber: spinbutton, кнопки, валюта, очистка и состояния. + */ + +const STORIES = [ + { id: 'components-form-inputnumber--buttons', name: 'Buttons' }, + { id: 'components-form-inputnumber--clearable', name: 'Clearable' }, + { id: 'components-form-inputnumber--currency', name: 'Currency' }, + { id: 'components-form-inputnumber--default', name: 'Default' }, + { id: 'components-form-inputnumber--disabled', name: 'Disabled' }, + { id: 'components-form-inputnumber--float-label', name: 'FloatLabel' }, + { id: 'components-form-inputnumber--labels', name: 'Labels' } +]; + +const smoke = (story) => ({ + name: `Smoke: ${story.name}`, + story: story.id, + run: async ({ page, expect, errors }) => { + expect(errors.filter((error) => error.type === 'pageerror').map((error) => error.text), 'ошибки страницы').toEqual([]); + expect(await page.locator('#storybook-root > *').count(), 'корень story').toBeGreaterThan(0); + const box = await page.locator('#storybook-root').boundingBox(); + expect(Boolean(box && box.width > 0), 'ширина story').toBe(true); + } +}); + +export default { + component: 'inputnumber', + stories: Object.fromEntries(STORIES.map((story) => [story.id, story.id])), + tests: [ + { + name: 'Default: role=spinbutton и ввод числа', + story: 'components-form-inputnumber--default', + run: async ({ page, expect }) => { + const input = page.locator('input').first(); + expect(await input.getAttribute('role'), 'role').toBe('spinbutton'); + await input.fill('42'); + expect(await input.inputValue(), 'значение').toBe('42'); + } + }, + { + name: 'Buttons: стрелки увеличивают и уменьшают значение', + story: 'components-form-inputnumber--buttons', + run: async ({ page, expect }) => { + const input = page.locator('input').first(); + await page.locator('.p-inputnumber-increment-button').click({ force: true }); + expect(await input.inputValue(), 'после +').toBe('1'); + await page.locator('.p-inputnumber-decrement-button').click({ force: true }); + expect(await input.inputValue(), 'после −').toBe('0'); + } + }, + { + name: 'Currency: значение с символом рубля', + story: 'components-form-inputnumber--currency', + run: async ({ page, expect }) => { + expect(await page.locator('input').first().inputValue(), 'значение').toContain('₽'); + } + }, + { + name: 'Clearable: иконка очищает значение', + story: 'components-form-inputnumber--clearable', + run: async ({ page, expect }) => { + const input = page.locator('input').first(); + await page.locator('.p-inputnumber-clear-icon').click(); + expect(await input.inputValue(), 'после очистки').toBe(''); + } + }, + { + name: 'Disabled: поле отключено', + story: 'components-form-inputnumber--disabled', + run: async ({ page, expect }) => { + expect(await page.locator('input').first().isDisabled(), 'disabled').toBe(true); + } + }, + ...STORIES.map(smoke), + { ...smoke(STORIES[0]), name: `Smoke: ${STORIES[0].name} (тёмная тема)`, theme: 'dark' } + ] +}; diff --git a/e2e/specs/inputotp.e2e.mjs b/e2e/specs/inputotp.e2e.mjs new file mode 100644 index 00000000..11585ae1 --- /dev/null +++ b/e2e/specs/inputotp.e2e.mjs @@ -0,0 +1,85 @@ +/** + * E2E-спека InputOTP: ячейки, авто-переход, маска и состояния. + */ + +const STORIES = [ + { id: 'components-form-inputotp--autofocus', name: 'Autofocus' }, + { id: 'components-form-inputotp--default', name: 'Default' }, + { id: 'components-form-inputotp--disabled', name: 'Disabled' }, + { id: 'components-form-inputotp--integer-only', name: 'IntegerOnly' }, + { id: 'components-form-inputotp--invalid', name: 'Invalid' }, + { id: 'components-form-inputotp--mask', name: 'Mask' } +]; + +const smoke = (story) => ({ + name: `Smoke: ${story.name}`, + story: story.id, + run: async ({ page, expect, errors }) => { + expect(errors.filter((error) => error.type === 'pageerror').map((error) => error.text), 'ошибки страницы').toEqual([]); + expect(await page.locator('#storybook-root > *').count(), 'корень story').toBeGreaterThan(0); + const box = await page.locator('#storybook-root').boundingBox(); + expect(Boolean(box && box.width > 0), 'ширина story').toBe(true); + } +}); + +export default { + component: 'inputotp', + stories: Object.fromEntries(STORIES.map((story) => [story.id, story.id])), + tests: [ + { + name: 'Default: четыре ячейки и переход фокуса', + story: 'components-form-inputotp--default', + run: async ({ page, expect }) => { + const inputs = page.locator('input.p-inputotp-input'); + expect(await inputs.count(), 'ячейки').toBe(4); + + await inputs.first().fill('1'); + expect(await page.evaluate(() => document.activeElement?.getAttribute('class')), 'фокус ушёл').toContain('p-inputotp-input'); + } + }, + { + name: 'Mask: ячейки скрывают ввод', + story: 'components-form-inputotp--mask', + run: async ({ page, expect }) => { + const types = await page.locator('input.p-inputotp-input').evaluateAll((elements) => elements.map((element) => element.type)); + expect(types, 'типы ячеек').toEqual(['password', 'password', 'password', 'password']); + } + }, + { + name: 'IntegerOnly: буква не принимается, цифра принимается', + story: 'components-form-inputotp--integer-only', + run: async ({ page, expect }) => { + const first = page.locator('input.p-inputotp-input').first(); + await first.focus(); + await page.keyboard.type('a'); + expect(await first.inputValue(), 'буква').toBe(''); + await page.keyboard.type('5'); + expect(await first.inputValue(), 'цифра').toBe('5'); + } + }, + { + name: 'Disabled: все ячейки отключены', + story: 'components-form-inputotp--disabled', + run: async ({ page, expect }) => { + const disabled = await page.locator('input.p-inputotp-input').evaluateAll((elements) => elements.map((element) => element.disabled)); + expect(disabled.every(Boolean), 'все disabled').toBe(true); + } + }, + { + name: 'Invalid: класс p-invalid', + story: 'components-form-inputotp--invalid', + run: async ({ page, expect }) => { + expect(await page.locator('input.p-inputotp-input').first().getAttribute('class'), 'invalid').toContain('p-invalid'); + } + }, + { + name: 'Autofocus: первая ячейка в фокусе', + story: 'components-form-inputotp--autofocus', + run: async ({ page, expect }) => { + expect(await page.evaluate(() => document.activeElement?.getAttribute('class')), 'фокус').toContain('p-inputotp-input'); + } + }, + ...STORIES.map(smoke), + { ...smoke(STORIES[0]), name: `Smoke: ${STORIES[0].name} (тёмная тема)`, theme: 'dark' } + ] +}; diff --git a/e2e/specs/inputtext.e2e.mjs b/e2e/specs/inputtext.e2e.mjs new file mode 100644 index 00000000..458322b4 --- /dev/null +++ b/e2e/specs/inputtext.e2e.mjs @@ -0,0 +1,174 @@ +/** + * E2E-спека InputText: ввод, лейблы, состояния, очистка и размеры. + * + * Проверяет контракт формы, а не вёрстку: значение, фокус, нативные атрибуты + * и доступность. Дефекты, которые сейчас воспроизводятся, помечены knownIssue. + */ + +const input = (page, index = 0) => page.locator('input').nth(index); +const clearIcon = (page) => page.locator('[aria-label="Очистить поле"]'); + +const a11yRulesWithoutDocumentNoise = { + 'landmark-one-main': { enabled: false }, + region: { enabled: false }, + 'page-has-heading-one': { enabled: false }, + 'scrollable-region-focusable': { enabled: false }, + 'color-contrast': { enabled: false } +}; + +export default { + component: 'inputtext', + stories: { + default: 'components-form-inputtext--default', + labels: 'components-form-inputtext--labels', + sizes: 'components-form-inputtext--sizes', + types: 'components-form-inputtext--types', + states: 'components-form-inputtext--states', + clearable: 'components-form-inputtext--clearable' + }, + tests: [ + { + name: 'Ввод обновляет значение поля', + story: 'default', + run: async ({ page, expect }) => { + const field = input(page); + expect(await field.count(), 'поле').toBe(1); + expect(await field.getAttribute('placeholder'), 'плейсхолдер').toBe('Введите текст...'); + + await field.fill('Привет'); + expect(await field.inputValue(), 'значение после ввода').toBe('Привет'); + expect(await field.evaluate((element) => element.classList.contains('p-filled')), 'класс p-filled').toBe(true); + } + }, + { + name: 'Лейбл связан с полем и фокусирует его по клику', + story: 'labels', + run: async ({ page, expect }) => { + const label = page.locator('label.extra-inputtext-label').first(); + const field = input(page); + const inputId = await field.getAttribute('id'); + + expect(await label.getAttribute('for'), 'for у лейбла').toBe(inputId); + + await label.click(); + expect(await page.evaluate(() => document.activeElement?.tagName), 'фокус после клика по лейблу').toBe('INPUT'); + expect(await page.evaluate(() => document.activeElement?.getAttribute('id')), 'id сфокусированного поля').toBe(inputId); + } + }, + { + name: 'Disabled: поле отключено и пропускается по Tab', + story: 'states', + run: async ({ page, expect }) => { + expect(await input(page, 1).isDisabled(), 'disabled-поле').toBe(true); + + await page.keyboard.press('Tab'); + expect(await page.evaluate(() => document.activeElement?.getAttribute('id')), 'первый Tab').toBe('extra-input-text-0'); + + await page.keyboard.press('Tab'); + expect(await page.evaluate(() => document.activeElement?.getAttribute('id')), 'второй Tab').toBe('extra-input-text-2'); + } + }, + { + name: 'Invalid: поле получает класс p-invalid', + story: 'states', + run: async ({ page, expect }) => { + expect(await input(page, 2).evaluate((element) => element.classList.contains('p-invalid')), 'класс p-invalid').toBe(true); + } + }, + { + name: 'Invalid: поле объявляет aria-invalid', + story: 'states', + knownIssue: 'PrimeNG ставит только класс p-invalid; aria-invalid на input отсутствует, скринридер не узнаёт об ошибке', + run: async ({ page, expect }) => { + expect(await input(page, 2).getAttribute('aria-invalid'), 'aria-invalid').toBe('true'); + } + }, + { + name: 'Размеры small/base/large/xlarge возрастают', + story: 'sizes', + run: async ({ page, expect }) => { + const heights = await page + .locator('input') + .evaluateAll((elements) => elements.map((element) => Math.round(element.getBoundingClientRect().height))); + + expect(heights.length, 'количество полей').toBe(4); + expect(heights[0] < heights[1], 'small ниже base').toBe(true); + expect(heights[1] < heights[2], 'base ниже large').toBe(true); + expect(heights[2] < heights[3], 'large ниже xlarge').toBe(true); + } + }, + { + name: 'Тип поля применяется: password скрывает ввод', + story: 'types', + run: async ({ page, expect }) => { + expect(await input(page, 1).getAttribute('type'), 'тип второго поля').toBe('password'); + } + }, + { + name: 'Очистка: иконка появляется только при значении и очищает поле', + story: 'clearable', + run: async ({ page, expect, wait }) => { + const field = input(page); + + expect(await clearIcon(page).count(), 'иконка при заполненном поле').toBe(1); + expect(await clearIcon(page).getAttribute('aria-label'), 'aria-label иконки').toBe('Очистить поле'); + expect(await clearIcon(page).getAttribute('tabindex'), 'tabindex иконки').toBe('0'); + + await clearIcon(page).click(); + await wait(async () => (await clearIcon(page).count()) === 0); + expect(await field.inputValue(), 'значение после очистки').toBe(''); + + await field.fill('Снова текст'); + await wait(async () => (await clearIcon(page).count()) === 1); + expect(await field.inputValue(), 'значение после повторного ввода').toBe('Снова текст'); + } + }, + { + name: 'Очистка с клавиатуры: Enter на иконке', + story: 'clearable', + run: async ({ page, expect, wait }) => { + const field = input(page); + await clearIcon(page).focus(); + await page.keyboard.press('Enter'); + await wait(async () => (await clearIcon(page).count()) === 0); + expect(await field.inputValue(), 'значение после Enter').toBe(''); + } + }, + { + name: 'После очистки фокус остаётся в поле', + story: 'clearable', + knownIssue: 'После клика по иконке очистки фокус уходит в body: клавиатурный пользователь теряет место', + run: async ({ page, expect }) => { + await clearIcon(page).click(); + await page.waitForTimeout(150); + + expect(await page.evaluate(() => document.activeElement?.tagName), 'активный элемент после очистки').toBe('INPUT'); + expect(await page.evaluate(() => document.activeElement?.getAttribute('id')), 'id активного поля').toBe('extra-input-text-0'); + } + }, + { + name: 'A11y: структура формы без critical/serious', + story: 'labels', + run: async ({ page, expect, a11y, formatViolations }) => { + const violations = await a11y({ rules: a11yRulesWithoutDocumentNoise }); + expect(violations, `нарушения axe: ${formatViolations(violations)}`).toEqual([]); + } + }, + { + name: 'A11y: контраст плавающего лейбла', + story: 'labels', + knownIssue: 'Цвет float-label — color.fg.muted (#85888e) на белом: 3.55:1 при норме 4.5:1', + run: async ({ page, expect, a11y, formatViolations }) => { + const violations = await a11y({ + rules: { + 'landmark-one-main': { enabled: false }, + region: { enabled: false }, + 'page-has-heading-one': { enabled: false }, + 'scrollable-region-focusable': { enabled: false } + } + }); + expect(violations, `нарушения axe: ${formatViolations(violations)}`).toEqual([]); + } + } + ] +}; diff --git a/e2e/specs/listbox.e2e.mjs b/e2e/specs/listbox.e2e.mjs new file mode 100644 index 00000000..5dd28840 --- /dev/null +++ b/e2e/specs/listbox.e2e.mjs @@ -0,0 +1,99 @@ +/** + * E2E-спека Listbox: выбор, множественный режим, фильтр, группы и состояния. + */ + +const STORIES = [ + { id: 'components-form-listbox--checkbox', name: 'Checkbox' }, + { id: 'components-form-listbox--checkmark', name: 'Checkmark' }, + { id: 'components-form-listbox--custom', name: 'Custom' }, + { id: 'components-form-listbox--default', name: 'Default' }, + { id: 'components-form-listbox--disabled', name: 'Disabled' }, + { id: 'components-form-listbox--filter', name: 'Filter' }, + { id: 'components-form-listbox--grouped', name: 'Grouped' }, + { id: 'components-form-listbox--multiple', name: 'Multiple' } +]; + +const smoke = (story) => ({ + name: `Smoke: ${story.name}`, + story: story.id, + run: async ({ page, expect, errors }) => { + expect(errors.filter((error) => error.type === 'pageerror').map((error) => error.text), 'ошибки страницы').toEqual([]); + expect(await page.locator('#storybook-root > *').count(), 'корень story').toBeGreaterThan(0); + const box = await page.locator('#storybook-root').boundingBox(); + expect(Boolean(box && box.width > 0), 'ширина story').toBe(true); + } +}); + +export default { + component: 'listbox', + stories: Object.fromEntries(STORIES.map((story) => [story.id, story.id])), + tests: [ + { + name: 'Default: role=listbox и выбор опции', + story: 'components-form-listbox--default', + run: async ({ page, expect }) => { + const list = page.locator('.p-listbox-list'); + expect(await list.getAttribute('role'), 'role списка').toBe('listbox'); + expect(await page.locator('.p-listbox-option').count(), 'опции').toBe(5); + + await page.locator('.p-listbox-option').nth(1).click(); + expect(await page.locator('.p-listbox-option-selected').count(), 'выбрано').toBe(1); + expect(await page.locator('.p-listbox-option-selected').innerText(), 'значение').toBe('Rome'); + } + }, + { + name: 'Multiple: два выбранных пункта', + story: 'components-form-listbox--multiple', + run: async ({ page, expect }) => { + await page.locator('.p-listbox-option').nth(0).click(); + await page.locator('.p-listbox-option').nth(2).click(); + expect(await page.locator('.p-listbox-option-selected').count(), 'выбрано').toBe(2); + } + }, + { + name: 'Checkbox: чекбоксы у опций и выбор', + story: 'components-form-listbox--checkbox', + run: async ({ page, expect }) => { + expect(await page.locator('.p-listbox-option .p-checkbox').count(), 'чекбоксы').toBe(5); + await page.locator('.p-listbox-option').first().click(); + expect(await page.locator('.p-listbox-option-selected').count(), 'выбрано').toBe(1); + } + }, + { + name: 'Filter: поиск оставляет London', + story: 'components-form-listbox--filter', + run: async ({ page, expect, wait }) => { + const filter = page.locator('input.p-listbox-filter'); + await filter.fill('lon'); + await wait(async () => (await page.locator('.p-listbox-option').count()) === 1); + expect(await page.locator('.p-listbox-option').innerText(), 'результат').toBe('London'); + } + }, + { + name: 'Grouped: две группы и шесть опций', + story: 'components-form-listbox--grouped', + run: async ({ page, expect }) => { + expect(await page.locator('.p-listbox-option-group').count(), 'группы').toBe(2); + expect(await page.locator('.p-listbox-option').count(), 'опции').toBe(6); + } + }, + { + name: 'Disabled: класс p-disabled и выбор не меняется', + story: 'components-form-listbox--disabled', + run: async ({ page, expect }) => { + expect(await page.locator('.p-listbox').getAttribute('class'), 'класс').toContain('p-disabled'); + await page.locator('.p-listbox-option').first().click({ force: true }); + expect(await page.locator('.p-listbox-option-selected').count(), 'выбрано').toBe(0); + } + }, + { + name: 'Custom: три опции с кастомным содержимым', + story: 'components-form-listbox--custom', + run: async ({ page, expect }) => { + expect(await page.locator('.p-listbox-option').count(), 'опции').toBe(3); + } + }, + ...STORIES.map(smoke), + { ...smoke(STORIES[0]), name: `Smoke: ${STORIES[0].name} (тёмная тема)`, theme: 'dark' } + ] +}; diff --git a/e2e/specs/megamenu.e2e.mjs b/e2e/specs/megamenu.e2e.mjs new file mode 100644 index 00000000..c5fc5a06 --- /dev/null +++ b/e2e/specs/megamenu.e2e.mjs @@ -0,0 +1,62 @@ +/** + * E2E-спека MegaMenu: корневые пункты, подменю, ориентация и закрытие. + */ + +const STORIES = [ + { id: 'components-menu-megamenu--custom', name: 'Custom' }, + { id: 'components-menu-megamenu--default', name: 'Default' }, + { id: 'components-menu-megamenu--horizontal', name: 'Horizontal' }, + { id: 'components-menu-megamenu--template', name: 'Template' }, + { id: 'components-menu-megamenu--vertical', name: 'Vertical' } +]; + +const smoke = (story) => ({ + name: `Smoke: ${story.name}`, + story: story.id, + run: async ({ page, expect, errors }) => { + expect(errors.filter((error) => error.type === 'pageerror').map((error) => error.text), 'ошибки страницы').toEqual([]); + expect(await page.locator('#storybook-root > *').count(), 'корень story').toBeGreaterThan(0); + const box = await page.locator('#storybook-root').boundingBox(); + expect(Boolean(box && box.width > 0), 'ширина story').toBe(true); + } +}); + +export default { + component: 'megamenu', + stories: Object.fromEntries(STORIES.map((story) => [story.id, story.id])), + tests: [ + { + name: 'Default: три корневых пункта и role=menubar', + story: 'components-menu-megamenu--default', + run: async ({ page, expect }) => { + expect(await page.locator('.p-megamenu-root-list').getAttribute('role'), 'role').toBe('menubar'); + expect(await page.locator('.p-megamenu-root-list > .p-megamenu-item').count(), 'корневые пункты').toBe(3); + } + }, + { + name: 'Default: подменю открывается и закрывается по Esc', + story: 'components-menu-megamenu--default', + run: async ({ page, expect }) => { + const first = page.locator('.p-megamenu-root-list > .p-megamenu-item').first(); + await first.locator('a').first().click(); + await page.waitForSelector('.p-megamenu-submenu', { state: 'visible' }); + + expect(await first.getAttribute('aria-expanded'), 'aria-expanded').toBe('true'); + expect(await page.locator('.p-megamenu-submenu').first().isVisible(), 'подменю').toBe(true); + + await page.keyboard.press('Escape'); + await page.waitForTimeout(300); + expect(await first.getAttribute('aria-expanded'), 'после Esc').toBe('false'); + } + }, + { + name: 'Vertical: вертикальная ориентация', + story: 'components-menu-megamenu--vertical', + run: async ({ page, expect }) => { + expect(await page.locator('.p-megamenu').getAttribute('class'), 'класс').toContain('p-megamenu-vertical'); + } + }, + ...STORIES.map(smoke), + { ...smoke(STORIES[0]), name: `Smoke: ${STORIES[0].name} (тёмная тема)`, theme: 'dark' } + ] +}; diff --git a/e2e/specs/menu.e2e.mjs b/e2e/specs/menu.e2e.mjs new file mode 100644 index 00000000..be53f359 --- /dev/null +++ b/e2e/specs/menu.e2e.mjs @@ -0,0 +1,76 @@ +/** + * E2E-спека Menu: пункты, иконки, всплывающее меню и закрытие по Esc. + */ + +const STORIES = [ + { id: 'components-menu-menu--basic', name: 'Basic' }, + { id: 'components-menu-menu--default', name: 'Default' }, + { id: 'components-menu-menu--grouped', name: 'Grouped' }, + { id: 'components-menu-menu--item-end', name: 'Item end slot' }, + { id: 'components-menu-menu--popup', name: 'Popup' }, + { id: 'components-menu-menu--with-icons', name: 'WithIcons' } +]; + +const smoke = (story) => ({ + name: `Smoke: ${story.name}`, + story: story.id, + run: async ({ page, expect, errors }) => { + expect(errors.filter((error) => error.type === 'pageerror').map((error) => error.text), 'ошибки страницы').toEqual([]); + expect(await page.locator('#storybook-root > *').count(), 'корень story').toBeGreaterThan(0); + const box = await page.locator('#storybook-root').boundingBox(); + expect(Boolean(box && box.width > 0), 'ширина story').toBe(true); + } +}); + +export default { + component: 'menu', + stories: Object.fromEntries(STORIES.map((story) => [story.id, story.id])), + tests: [ + { + name: 'Default: три пункта с ролью menuitem', + story: 'components-menu-menu--default', + run: async ({ page, expect }) => { + expect(await page.locator('.p-menu-item[role=menuitem]').count(), 'пункты').toBe(3); + expect(await page.locator('.p-menu-item-link').allInnerTexts(), 'тексты').toEqual([ + 'Кабинет', + 'Скачать реестр\nCtrl+E', + 'Выйти' + ]); + } + }, + { + name: 'Popup: кнопка открывает меню, Esc закрывает', + story: 'components-menu-menu--popup', + run: async ({ page, expect }) => { + const trigger = page.locator('button.p-button', { hasText: 'Действия с заказом' }); + await trigger.click(); + await page.waitForSelector('.p-menu', { state: 'visible' }); + expect(await page.locator('.p-menu-item').count(), 'пункты').toBeGreaterThan(0); + + await page.keyboard.press('Escape'); + await page.waitForSelector('.p-menu', { state: 'detached' }); + expect(await page.locator('.p-menu').count(), 'после Esc').toBe(0); + } + }, + { + name: 'WithIcons: иконки у пунктов', + story: 'components-menu-menu--with-icons', + run: async ({ page, expect }) => { + expect(await page.locator('.p-menu-item .ti').count(), 'иконки').toBeGreaterThan(0); + } + }, + { + name: 'Popup: кнопка объявляет aria-expanded', + story: 'components-menu-menu--popup', + knownIssue: 'Кнопка-триггер меню не имеет aria-expanded/aria-haspopup: состояние меню не объявляется', + run: async ({ page, expect }) => { + const trigger = page.locator('button.p-button', { hasText: 'Действия с заказом' }); + const expanded = await trigger.getAttribute('aria-expanded'); + const haspopup = await trigger.getAttribute('aria-haspopup'); + expect(expanded !== null && haspopup !== null, 'aria-состояние').toBe(true); + } + }, + ...STORIES.map(smoke), + { ...smoke(STORIES[0]), name: `Smoke: ${STORIES[0].name} (тёмная тема)`, theme: 'dark' } + ] +}; diff --git a/e2e/specs/menubar.e2e.mjs b/e2e/specs/menubar.e2e.mjs new file mode 100644 index 00000000..01fc6c46 --- /dev/null +++ b/e2e/specs/menubar.e2e.mjs @@ -0,0 +1,71 @@ +/** + * E2E-спека Menubar: корневые пункты, подменю и иконки. + */ + +const STORIES = [ + { id: 'components-menu-menubar--basic', name: 'Basic' }, + { id: 'components-menu-menubar--custom', name: 'Custom' }, + { id: 'components-menu-menubar--with-icon', name: 'WithIcon' } +]; + +const smoke = (story) => ({ + name: `Smoke: ${story.name}`, + story: story.id, + run: async ({ page, expect, errors }) => { + expect(errors.filter((error) => error.type === 'pageerror').map((error) => error.text), 'ошибки страницы').toEqual([]); + expect(await page.locator('#storybook-root > *').count(), 'корень story').toBeGreaterThan(0); + const box = await page.locator('#storybook-root').boundingBox(); + expect(Boolean(box && box.width > 0), 'ширина story').toBe(true); + } +}); + +export default { + component: 'menubar', + stories: Object.fromEntries(STORIES.map((story) => [story.id, story.id])), + tests: [ + { + name: 'Basic: role=menubar и три корневых пункта', + story: 'components-menu-menubar--basic', + run: async ({ page, expect }) => { + expect(await page.locator('.p-menubar-root-list').getAttribute('role'), 'role').toBe('menubar'); + const items = page.locator('.p-menubar-root-list > .p-menubar-item'); + expect(await items.count(), 'корневые пункты').toBe(3); + expect(await items.first().getAttribute('role'), 'role пункта').toBe('menuitem'); + } + }, + { + name: 'Basic: подменю открывается и закрывается по Esc', + story: 'components-menu-menubar--basic', + run: async ({ page, expect }) => { + const second = page.locator('.p-menubar-root-list > .p-menubar-item').nth(1); + await second.locator('a').first().click(); + await page.waitForSelector('.p-menubar-submenu', { state: 'visible' }); + expect(await page.locator('.p-menubar-submenu').first().isVisible(), 'подменю').toBe(true); + + await page.keyboard.press('Escape'); + await page.waitForTimeout(300); + expect(await page.locator('.p-menubar-submenu').first().isVisible(), 'после Esc').toBe(false); + } + }, + { + name: 'WithIcon: иконки в пунктах', + story: 'components-menu-menubar--with-icon', + run: async ({ page, expect }) => { + expect(await page.locator('.p-menubar .ti').count(), 'иконки').toBeGreaterThan(0); + } + }, + { + name: 'Basic: пункт с подменю объявляет aria-expanded', + story: 'components-menu-menubar--basic', + knownIssue: 'У пункта с подменю нет aria-haspopup/aria-expanded: состояние подменю не объявляется', + run: async ({ page, expect }) => { + const link = page.locator('.p-menubar-root-list > .p-menubar-item').nth(1).locator('a').first(); + const haspopup = await link.getAttribute('aria-haspopup'); + const expanded = await link.getAttribute('aria-expanded'); + expect(haspopup !== null || expanded !== null, 'aria-состояние').toBe(true); + } + }, + ...STORIES.map(smoke), + { ...smoke(STORIES[0]), name: `Smoke: ${STORIES[0].name} (тёмная тема)`, theme: 'dark' } + ] +}; diff --git a/e2e/specs/message.e2e.mjs b/e2e/specs/message.e2e.mjs new file mode 100644 index 00000000..262b6959 --- /dev/null +++ b/e2e/specs/message.e2e.mjs @@ -0,0 +1,86 @@ +/** + * E2E-спека Message: severity, закрытие и доступность кнопки закрытия. + */ + +const STORIES = [ + { id: 'components-feedback-message--default', name: 'Info' }, + { id: 'components-feedback-message--severity', name: 'Severity' }, + { id: 'components-feedback-message--slots', name: 'Slots' }, + { id: 'components-feedback-message--timer', name: 'Timer' }, + { id: 'components-feedback-message--with-close', name: 'WithClose' }, + { id: 'components-feedback-message--with-icon', name: 'WithIcon' } +]; + +const smoke = (story) => ({ + name: `Smoke: ${story.name}`, + story: story.id, + run: async ({ page, expect, errors }) => { + expect(errors.filter((error) => error.type === 'pageerror').map((error) => error.text), 'ошибки страницы').toEqual([]); + expect(await page.locator('#storybook-root > *').count(), 'корень story').toBeGreaterThan(0); + const box = await page.locator('#storybook-root').boundingBox(); + expect(Boolean(box && box.width > 0), 'ширина story').toBe(true); + } +}); + +export default { + component: 'message', + stories: Object.fromEntries(STORIES.map((story) => [story.id, story.id])), + tests: [ + { + name: 'Info: role=alert, severity info и текст', + story: 'components-feedback-message--default', + run: async ({ page, expect }) => { + const message = page.locator('.p-message'); + expect(await message.getAttribute('role'), 'role').toBe('alert'); + expect(await message.getAttribute('class'), 'severity').toContain('p-message-info'); + expect(await message.innerText(), 'текст').toContain('Message'); + } + }, + { + name: 'Severity: четыре варианта', + story: 'components-feedback-message--severity', + run: async ({ page, expect }) => { + const classes = await page.locator('.p-message').evaluateAll((elements) => elements.map((element) => element.className)); + expect(classes.length, 'количество').toBe(4); + expect(classes[0], 'info').toContain('p-message-info'); + expect(classes[1], 'success').toContain('p-message-success'); + expect(classes[2], 'warn').toContain('p-message-warn'); + expect(classes[3], 'error').toContain('p-message-error'); + } + }, + { + name: 'Message: класс severity не должен содержать undefined', + story: 'components-feedback-message--severity', + knownIssue: 'PrimeNG добавляет p-message-undefined к каждому сообщению: класс собирается из незаполненного severity', + run: async ({ page, expect }) => { + const classes = await page.locator('.p-message').evaluateAll((elements) => elements.map((element) => element.className)); + expect(classes.some((className) => className.includes('p-message-undefined')), 'класс с undefined').toBe(false); + } + }, + { + name: 'WithClose: кнопки закрытия удаляют сообщение', + story: 'components-feedback-message--with-close', + run: async ({ page, expect, wait }) => { + expect(await page.locator('.p-message').count(), 'сообщения').toBe(4); + expect(await page.locator('.p-message-close-button').count(), 'кнопки').toBe(4); + + await page.locator('.p-message-close-button').first().click(); + await wait(async () => (await page.locator('.p-message').count()) === 3); + expect(await page.locator('.p-message').count(), 'после закрытия').toBe(3); + } + }, + { + name: 'WithClose: у кнопки закрытия есть доступное имя', + story: 'components-feedback-message--with-close', + knownIssue: 'p-message-close-button не имеет aria-label/title: скринридер не называет кнопку', + run: async ({ page, expect }) => { + const name = await page.locator('.p-message-close-button').first().evaluate((element) => { + return element.getAttribute('aria-label') || element.getAttribute('title') || element.textContent.trim(); + }); + expect(Boolean(name), 'доступное имя').toBe(true); + } + }, + ...STORIES.map(smoke), + { ...smoke(STORIES[0]), name: `Smoke: ${STORIES[0].name} (тёмная тема)`, theme: 'dark' } + ] +}; diff --git a/e2e/specs/metergroup.e2e.mjs b/e2e/specs/metergroup.e2e.mjs new file mode 100644 index 00000000..f11edd44 --- /dev/null +++ b/e2e/specs/metergroup.e2e.mjs @@ -0,0 +1,62 @@ +/** + * E2E-спека MeterGroup: значения, ориентация и подписи. + */ + +const STORIES = [ + { id: 'components-misc-metergroup--default', name: 'Default' }, + { id: 'components-misc-metergroup--horizontal', name: 'Horizontal' }, + { id: 'components-misc-metergroup--icon', name: 'Icon' }, + { id: 'components-misc-metergroup--label-start', name: 'LabelStart' }, + { id: 'components-misc-metergroup--label-vertical', name: 'LabelVertical' }, + { id: 'components-misc-metergroup--vertical', name: 'Vertical' } +]; + +const smoke = (story) => ({ + name: `Smoke: ${story.name}`, + story: story.id, + run: async ({ page, expect, errors }) => { + expect(errors.filter((error) => error.type === 'pageerror').map((error) => error.text), 'ошибки страницы').toEqual([]); + expect(await page.locator('#storybook-root > *').count(), 'корень story').toBeGreaterThan(0); + const box = await page.locator('#storybook-root').boundingBox(); + expect(Boolean(box && box.width > 0), 'ширина story').toBe(true); + } +}); + +export default { + component: 'metergroup', + stories: Object.fromEntries(STORIES.map((story) => [story.id, story.id])), + tests: [ + { + name: 'Default: meter, значение 48 и три сегмента', + story: 'components-misc-metergroup--default', + run: async ({ page, expect }) => { + const group = page.locator('.p-metergroup'); + expect(await group.getAttribute('role'), 'role').toBe('meter'); + expect(await group.getAttribute('aria-valuenow'), 'aria-valuenow').toBe('48'); + expect(await group.getAttribute('aria-label'), 'aria-label').toBe('Использование диска'); + expect(await page.locator('.p-metergroup-meter').count(), 'сегменты').toBe(3); + expect(await page.locator('.p-metergroup-label').count(), 'подписи').toBe(3); + } + }, + { + name: 'Vertical: вертикальная ориентация', + story: 'components-misc-metergroup--vertical', + run: async ({ page, expect }) => { + expect(await page.locator('.p-metergroup').getAttribute('class'), 'класс').toContain('p-metergroup-vertical'); + } + }, + { + name: 'LabelVertical: подписи на всю ширину', + story: 'components-misc-metergroup--label-vertical', + run: async ({ page, expect }) => { + const widths = await page.locator('.p-metergroup-label').evaluateAll((labels) => + labels.map((label) => Math.round(label.getBoundingClientRect().width)) + ); + expect(widths.length, 'подписи').toBe(3); + expect(widths.every((width) => width > 1000), 'широкие подписи').toBe(true); + } + }, + ...STORIES.map(smoke), + { ...smoke(STORIES[0]), name: `Smoke: ${STORIES[0].name} (тёмная тема)`, theme: 'dark' } + ] +}; diff --git a/e2e/specs/multiselect.e2e.mjs b/e2e/specs/multiselect.e2e.mjs new file mode 100644 index 00000000..6f96d40c --- /dev/null +++ b/e2e/specs/multiselect.e2e.mjs @@ -0,0 +1,112 @@ +/** + * E2E-спека MultiSelect: оверлей, выбор, чипы, группы и состояния. + */ + +const STORIES = [ + { id: 'components-form-multiselect--chips', name: 'Chips' }, + { id: 'components-form-multiselect--default', name: 'Default' }, + { id: 'components-form-multiselect--disabled', name: 'Disabled' }, + { id: 'components-form-multiselect--grouped', name: 'Grouped' }, + { id: 'components-form-multiselect--invalid', name: 'Invalid' }, + { id: 'components-form-multiselect--labels', name: 'Labels' } +]; + +const smoke = (story) => ({ + name: `Smoke: ${story.name}`, + story: story.id, + run: async ({ page, expect, errors }) => { + expect(errors.filter((error) => error.type === 'pageerror').map((error) => error.text), 'ошибки страницы').toEqual([]); + expect(await page.locator('#storybook-root > *').count(), 'корень story').toBeGreaterThan(0); + const box = await page.locator('#storybook-root').boundingBox(); + expect(Boolean(box && box.width > 0), 'ширина story').toBe(true); + } +}); + +const openOverlay = async (page) => { + await page.locator('.p-multiselect-label').click(); + await page.waitForSelector('.p-multiselect-overlay', { state: 'visible' }); +}; + +export default { + component: 'multiselect', + stories: Object.fromEntries(STORIES.map((story) => [story.id, story.id])), + tests: [ + { + name: 'Default: combobox, открытие, пять опций и выбор', + story: 'components-form-multiselect--default', + run: async ({ page, expect }) => { + const hidden = page.locator('input[role=combobox]'); + expect(await hidden.count(), 'скрытый combobox').toBe(1); + expect(await hidden.getAttribute('aria-expanded'), 'до открытия').toBe('false'); + + await openOverlay(page); + expect(await hidden.getAttribute('aria-expanded'), 'после открытия').toBe('true'); + expect(await page.locator('.p-multiselect-option').count(), 'опции').toBe(5); + expect(await page.locator('.p-multiselect-option[role=option]').count(), 'role=option').toBe(5); + + await page.locator('.p-multiselect-option').first().click(); + expect(await page.locator('#storybook-root').innerText(), 'выбранное значение').toContain('Новосибирск'); + } + }, + { + name: 'Chips: два выбора дают два чипа', + story: 'components-form-multiselect--chips', + run: async ({ page, expect }) => { + await openOverlay(page); + expect(await page.locator('.p-multiselect-option').count(), 'опции').toBe(4); + + await page.locator('.p-multiselect-option').nth(0).click(); + await page.locator('.p-multiselect-option').nth(1).click(); + expect(await page.locator('.p-multiselect-chip').count(), 'чипы').toBe(2); + + await page.keyboard.press('Escape'); + expect(await page.locator('input[role=combobox]').getAttribute('aria-expanded'), 'после Esc').toBe('false'); + } + }, + { + name: 'Grouped: две группы и шесть опций', + story: 'components-form-multiselect--grouped', + run: async ({ page, expect }) => { + await openOverlay(page); + expect(await page.locator('.p-multiselect-option-group').count(), 'группы').toBe(2); + expect(await page.locator('.p-multiselect-option').count(), 'опции').toBe(6); + } + }, + { + name: 'Disabled: класс p-disabled и оверлей не открывается', + story: 'components-form-multiselect--disabled', + run: async ({ page, expect }) => { + expect(await page.locator('.p-multiselect').getAttribute('class'), 'класс').toContain('p-disabled'); + await page.locator('.p-multiselect').click({ force: true }); + await page.waitForTimeout(300); + expect(await page.locator('.p-multiselect-overlay').count(), 'оверлей').toBe(0); + } + }, + { + name: 'Invalid: класс p-invalid', + story: 'components-form-multiselect--invalid', + run: async ({ page, expect }) => { + expect(await page.locator('.p-multiselect').getAttribute('class'), 'invalid').toContain('p-invalid'); + } + }, + { + name: 'Labels: лейбл связан с полем', + story: 'components-form-multiselect--labels', + run: async ({ page, expect }) => { + const label = page.locator('label').first(); + const target = await label.getAttribute('for'); + expect(target, 'for').toBeTruthy(); + expect(await page.evaluate((id) => Boolean(document.getElementById(id)), target), 'элемент с id').toBe(true); + } + }, + { + name: 'Disabled: combobox объявлен aria-disabled', + story: 'components-form-multiselect--disabled', + run: async ({ page, expect }) => { + expect(await page.locator('input[role=combobox]').getAttribute('aria-disabled'), 'aria-disabled').toBe('true'); + } + }, + ...STORIES.map(smoke), + { ...smoke(STORIES[0]), name: `Smoke: ${STORIES[0].name} (тёмная тема)`, theme: 'dark' } + ] +}; diff --git a/e2e/specs/paginator.e2e.mjs b/e2e/specs/paginator.e2e.mjs new file mode 100644 index 00000000..14f13514 --- /dev/null +++ b/e2e/specs/paginator.e2e.mjs @@ -0,0 +1,64 @@ +/** + * E2E-спека Paginator: страницы, переходы, отчёт и размер страницы. + */ + +const STORIES = [ + { id: 'components-data-paginator--current-page-report', name: 'Current Page Report' }, + { id: 'components-data-paginator--default', name: 'Default' }, + { id: 'components-data-paginator--rows-per-page', name: 'Rows Per Page' } +]; + +const smoke = (story) => ({ + name: `Smoke: ${story.name}`, + story: story.id, + run: async ({ page, expect, errors }) => { + expect(errors.filter((error) => error.type === 'pageerror').map((error) => error.text), 'ошибки страницы').toEqual([]); + expect(await page.locator('#storybook-root > *').count(), 'корень story').toBeGreaterThan(0); + const box = await page.locator('#storybook-root').boundingBox(); + expect(Boolean(box && box.width > 0), 'ширина story').toBe(true); + } +}); + +export default { + component: 'paginator', + stories: Object.fromEntries(STORIES.map((story) => [story.id, story.id])), + tests: [ + { + name: 'Default: пять страниц, первая выбрана, prev disabled', + story: 'components-data-paginator--default', + run: async ({ page, expect }) => { + expect(await page.locator('.p-paginator-page').count(), 'страницы').toBe(5); + expect(await page.locator('.p-paginator-page-selected').innerText(), 'текущая').toBe('1'); + expect(await page.locator('.p-paginator-prev').getAttribute('class'), 'prev disabled').toContain('p-disabled'); + expect(await page.locator('.p-paginator-next').getAttribute('aria-label'), 'aria-label next').toBe('Следующая страница'); + } + }, + { + name: 'Default: Next переключает на вторую страницу', + story: 'components-data-paginator--default', + run: async ({ page, expect }) => { + await page.locator('.p-paginator-next').click(); + expect(await page.locator('.p-paginator-page-selected').innerText(), 'текущая').toBe('2'); + expect((await page.locator('.p-paginator-prev').getAttribute('class')).includes('p-disabled'), 'prev стал активен').toBe(false); + } + }, + { + name: 'Current Page Report: 1 из 12 и переход', + story: 'components-data-paginator--current-page-report', + run: async ({ page, expect }) => { + expect(await page.locator('.p-paginator-current').innerText(), 'отчёт').toBe('1 из 12'); + await page.locator('.p-paginator-next').click(); + expect(await page.locator('.p-paginator-current').innerText(), 'после Next').toBe('2 из 12'); + } + }, + { + name: 'Rows Per Page: выбор 10 строк', + story: 'components-data-paginator--rows-per-page', + run: async ({ page, expect }) => { + expect(await page.locator('.p-paginator-rpp-dropdown').innerText(), 'значение').toContain('10'); + } + }, + ...STORIES.map(smoke), + { ...smoke(STORIES[0]), name: `Smoke: ${STORIES[0].name} (тёмная тема)`, theme: 'dark' } + ] +}; diff --git a/e2e/specs/panelmenu.e2e.mjs b/e2e/specs/panelmenu.e2e.mjs new file mode 100644 index 00000000..04b6d0ba --- /dev/null +++ b/e2e/specs/panelmenu.e2e.mjs @@ -0,0 +1,64 @@ +/** + * E2E-спека PanelMenu: заголовки, раскрытие панелей и disabled. + */ + +const STORIES = [ + { id: 'components-menu-panelmenu--basic', name: 'Basic' }, + { id: 'components-menu-panelmenu--custom', name: 'Custom' }, + { id: 'components-menu-panelmenu--default', name: 'Default' }, + { id: 'components-menu-panelmenu--multiple', name: 'Multiple' } +]; + +const smoke = (story) => ({ + name: `Smoke: ${story.name}`, + story: story.id, + run: async ({ page, expect, errors }) => { + expect(errors.filter((error) => error.type === 'pageerror').map((error) => error.text), 'ошибки страницы').toEqual([]); + expect(await page.locator('#storybook-root > *').count(), 'корень story').toBeGreaterThan(0); + const box = await page.locator('#storybook-root').boundingBox(); + expect(Boolean(box && box.width > 0), 'ширина story').toBe(true); + } +}); + +const visibleContents = (page) => + page.locator('.p-panelmenu-content').evaluateAll((contents) => contents.filter((content) => content.offsetParent !== null).length); + +export default { + component: 'panelmenu', + stories: Object.fromEntries(STORIES.map((story) => [story.id, story.id])), + tests: [ + { + name: 'Default: четыре заголовка и раскрытая панель', + story: 'components-menu-panelmenu--default', + run: async ({ page, expect }) => { + expect(await page.locator('.p-panelmenu-header').count(), 'заголовки').toBe(4); + expect(await visibleContents(page), 'видимые панели').toBeGreaterThanOrEqual(1); + } + }, + { + name: 'Default: клик по заголовку сворачивает панель', + story: 'components-menu-panelmenu--default', + knownIssue: 'Клик по заголовку не меняет aria-expanded и не сворачивает панель', + run: async ({ page, expect }) => { + const before = await visibleContents(page); + await page.locator('.p-panelmenu-header').first().click(); + expect(await visibleContents(page), 'после сворачивания').toBe(before - 1); + await page.locator('.p-panelmenu-header').first().click(); + expect(await visibleContents(page), 'после разворачивания').toBe(before); + } + }, + { + name: 'Default: disabled-заголовок не раскрывается', + story: 'components-menu-panelmenu--default', + run: async ({ page, expect }) => { + const disabled = page.locator('.p-panelmenu-header.p-disabled'); + expect(await disabled.count(), 'disabled-заголовок').toBe(1); + const before = await visibleContents(page); + await disabled.click({ force: true }); + expect(await visibleContents(page), 'панели').toBe(before); + } + }, + ...STORIES.map(smoke), + { ...smoke(STORIES[0]), name: `Smoke: ${STORIES[0].name} (тёмная тема)`, theme: 'dark' } + ] +}; diff --git a/e2e/specs/password.e2e.mjs b/e2e/specs/password.e2e.mjs new file mode 100644 index 00000000..a020d4be --- /dev/null +++ b/e2e/specs/password.e2e.mjs @@ -0,0 +1,95 @@ +/** + * E2E-спека Password: маска, переключение видимости, feedback и состояния. + */ + +const STORIES = [ + { id: 'components-form-password--default', name: 'Default' }, + { id: 'components-form-password--disabled', name: 'Disabled' }, + { id: 'components-form-password--feedback', name: 'Feedback' }, + { id: 'components-form-password--float-label', name: 'FloatLabel' }, + { id: 'components-form-password--header', name: 'Header' }, + { id: 'components-form-password--invalid', name: 'Invalid' }, + { id: 'components-form-password--template', name: 'Template' }, + { id: 'components-form-password--toggle-mask', name: 'ToggleMask' } +]; + +const smoke = (story) => ({ + name: `Smoke: ${story.name}`, + story: story.id, + run: async ({ page, expect, errors }) => { + expect(errors.filter((error) => error.type === 'pageerror').map((error) => error.text), 'ошибки страницы').toEqual([]); + expect(await page.locator('#storybook-root > *').count(), 'корень story').toBeGreaterThan(0); + const box = await page.locator('#storybook-root').boundingBox(); + expect(Boolean(box && box.width > 0), 'ширина story').toBe(true); + } +}); + +export default { + component: 'password', + stories: Object.fromEntries(STORIES.map((story) => [story.id, story.id])), + tests: [ + { + name: 'Default: ввод скрыт', + story: 'components-form-password--default', + run: async ({ page, expect }) => { + const input = page.locator('input.p-password-input'); + expect(await input.getAttribute('type'), 'тип').toBe('password'); + await input.fill('secret123'); + expect(await input.inputValue(), 'значение').toBe('secret123'); + } + }, + { + name: 'ToggleMask: иконка показывает и скрывает пароль', + story: 'components-form-password--toggle-mask', + run: async ({ page, expect }) => { + const input = page.locator('input.p-password-input'); + const toggle = page.locator('.p-password-toggle-mask-icon'); + expect(await input.getAttribute('type'), 'до').toBe('password'); + + await toggle.click(); + expect(await input.getAttribute('type'), 'после показа').toBe('text'); + await toggle.click(); + expect(await input.getAttribute('type'), 'после скрытия').toBe('password'); + } + }, + { + name: 'Feedback: индикатор сложности появляется при вводе', + story: 'components-form-password--feedback', + run: async ({ page, expect }) => { + await page.locator('input.p-password-input').fill('abc'); + expect(await page.locator('.p-password-meter').count(), 'индикатор').toBe(1); + } + }, + { + name: 'Disabled: поле отключено', + story: 'components-form-password--disabled', + run: async ({ page, expect }) => { + expect(await page.locator('input.p-password-input').isDisabled(), 'disabled').toBe(true); + } + }, + { + name: 'Invalid: класс p-invalid', + story: 'components-form-password--invalid', + run: async ({ page, expect }) => { + expect(await page.locator('input.p-password-input').getAttribute('class'), 'invalid').toContain('p-invalid'); + } + }, + { + name: 'ToggleMask: иконка доступна с клавиатуры', + story: 'components-form-password--toggle-mask', + knownIssue: 'Иконка переключения — svg без role/aria-label/tabindex: недоступна скринридеру и с клавиатуры', + run: async ({ page, expect }) => { + const icon = page.locator('.p-password-toggle-mask-icon'); + const accessible = await icon.evaluate((element) => { + const role = element.getAttribute('role'); + const label = element.getAttribute('aria-label'); + const tabindex = element.getAttribute('tabindex'); + return Boolean(role && label) || tabindex === '0'; + }); + expect(accessible, 'иконка доступна').toBe(true); + } + }, + ...STORIES.map(smoke), + { ...smoke(STORIES[0]), name: `Smoke: ${STORIES[0].name} (тёмная тема)`, theme: 'dark' } + ] +}; diff --git a/e2e/specs/popover.e2e.mjs b/e2e/specs/popover.e2e.mjs new file mode 100644 index 00000000..21c63744 --- /dev/null +++ b/e2e/specs/popover.e2e.mjs @@ -0,0 +1,65 @@ +/** + * E2E-спека Popover: открытие, закрытие и доступность диалога. + */ + +const STORIES = [ + { id: 'components-overlay-popover--default', name: 'Default' }, + { id: 'components-overlay-popover--rich-content', name: 'RichContent' } +]; + +const smoke = (story) => ({ + name: `Smoke: ${story.name}`, + story: story.id, + run: async ({ page, expect, errors }) => { + expect(errors.filter((error) => error.type === 'pageerror').map((error) => error.text), 'ошибки страницы').toEqual([]); + expect(await page.locator('#storybook-root > *').count(), 'корень story').toBeGreaterThan(0); + const box = await page.locator('#storybook-root').boundingBox(); + expect(Boolean(box && box.width > 0), 'ширина story').toBe(true); + } +}); + +const openPopover = async (page) => { + await page.locator('button', { hasText: 'Показать' }).click(); + await page.waitForSelector('.p-popover', { state: 'visible' }); +}; + +export default { + component: 'popover', + stories: Object.fromEntries(STORIES.map((story) => [story.id, story.id])), + tests: [ + { + name: 'Default: поповер открывается и закрывается кликом вне', + story: 'components-overlay-popover--default', + run: async ({ page, expect }) => { + await openPopover(page); + expect(await page.locator('.p-popover').isVisible(), 'поповер').toBe(true); + await page.mouse.click(1000, 700); + await page.waitForTimeout(400); + expect(await page.locator('.p-popover').isVisible().catch(() => false), 'после клика вне').toBe(false); + } + }, + { + name: 'Default: у поповера есть доступное имя', + story: 'components-overlay-popover--default', + knownIssue: 'p-popover имеет role=dialog без aria-label/aria-labelledby', + knownIssue: 'p-popover имеет role=dialog без aria-label/aria-labelledby', + run: async ({ page, expect }) => { + await openPopover(page); + const popover = page.locator('.p-popover'); + const label = await popover.getAttribute('aria-label'); + const labelledBy = await popover.getAttribute('aria-labelledby'); + expect(Boolean(label || labelledBy), 'доступное имя').toBe(true); + } + }, + { + name: 'RichContent: содержимое поповера', + story: 'components-overlay-popover--rich-content', + run: async ({ page, expect }) => { + await openPopover(page); + expect((await page.locator('.p-popover').innerText()).trim().length, 'контент').toBeGreaterThan(0); + } + }, + ...STORIES.map(smoke), + { ...smoke(STORIES[0]), name: `Smoke: ${STORIES[0].name} (тёмная тема)`, theme: 'dark' } + ] +}; diff --git a/e2e/specs/progressbar.e2e.mjs b/e2e/specs/progressbar.e2e.mjs new file mode 100644 index 00000000..c9a2faed --- /dev/null +++ b/e2e/specs/progressbar.e2e.mjs @@ -0,0 +1,61 @@ +/** + * E2E-спека ProgressBar: значение, indeterminate и подпись. + */ + +const STORIES = [ + { id: 'components-misc-progressbar--default', name: 'Default' }, + { id: 'components-misc-progressbar--indeterminate', name: 'Indeterminate' }, + { id: 'components-misc-progressbar--no-label', name: 'No Label' } +]; + +const smoke = (story) => ({ + name: `Smoke: ${story.name}`, + story: story.id, + run: async ({ page, expect, errors }) => { + expect(errors.filter((error) => error.type === 'pageerror').map((error) => error.text), 'ошибки страницы').toEqual([]); + expect(await page.locator('#storybook-root > *').count(), 'корень story').toBeGreaterThan(0); + const box = await page.locator('#storybook-root').boundingBox(); + expect(Boolean(box && box.width > 0), 'ширина story').toBe(true); + } +}); + +export default { + component: 'progressbar', + stories: Object.fromEntries(STORIES.map((story) => [story.id, story.id])), + tests: [ + { + name: 'Default: aria-valuenow 50, подпись и половина полосы', + story: 'components-misc-progressbar--default', + run: async ({ page, expect }) => { + const bar = page.locator('.p-progressbar'); + expect(await bar.getAttribute('role'), 'role').toBe('progressbar'); + expect(await bar.getAttribute('aria-valuenow'), 'aria-valuenow').toBe('50'); + expect(await bar.getAttribute('aria-label'), 'aria-label').toBe('Загрузка данных'); + expect(await page.locator('.p-progressbar-label').innerText(), 'подпись').toBe('50%'); + + const total = await bar.boundingBox(); + const value = await page.locator('.p-progressbar-value').boundingBox(); + expect(Math.abs(value.width / total.width - 0.5) < 0.05, 'половина полосы').toBe(true); + } + }, + { + name: 'Indeterminate: класс и отсутствие aria-valuenow', + story: 'components-misc-progressbar--indeterminate', + run: async ({ page, expect }) => { + const bar = page.locator('.p-progressbar'); + expect(await bar.getAttribute('class'), 'класс').toContain('p-progressbar-indeterminate'); + expect(await bar.getAttribute('aria-valuenow'), 'aria-valuenow').toBe(null); + } + }, + { + name: 'No Label: подпись пустая', + story: 'components-misc-progressbar--no-label', + run: async ({ page, expect }) => { + expect(await page.locator('.p-progressbar-label').innerText(), 'подпись').toBe(''); + expect(await page.locator('.p-progressbar').getAttribute('aria-valuenow'), 'aria-valuenow').toBe('60'); + } + }, + ...STORIES.map(smoke), + { ...smoke(STORIES[0]), name: `Smoke: ${STORIES[0].name} (тёмная тема)`, theme: 'dark' } + ] +}; diff --git a/e2e/specs/progressspinner.e2e.mjs b/e2e/specs/progressspinner.e2e.mjs new file mode 100644 index 00000000..f99e6db6 --- /dev/null +++ b/e2e/specs/progressspinner.e2e.mjs @@ -0,0 +1,58 @@ +/** + * E2E-спека ProgressSpinner: размеры, доступность и монохром. + */ + +const STORIES = [ + { id: 'components-misc-progressspinner--default', name: 'Default' }, + { id: 'components-misc-progressspinner--monochrome', name: 'Monochrome' }, + { id: 'components-misc-progressspinner--sizes', name: 'Sizes' } +]; + +const smoke = (story) => ({ + name: `Smoke: ${story.name}`, + story: story.id, + run: async ({ page, expect, errors }) => { + expect(errors.filter((error) => error.type === 'pageerror').map((error) => error.text), 'ошибки страницы').toEqual([]); + expect(await page.locator('#storybook-root > *').count(), 'корень story').toBeGreaterThan(0); + const box = await page.locator('#storybook-root').boundingBox(); + expect(Boolean(box && box.width > 0), 'ширина story').toBe(true); + } +}); + +export default { + component: 'progressspinner', + stories: Object.fromEntries(STORIES.map((story) => [story.id, story.id])), + tests: [ + { + name: 'Sizes: 16 < 32 < 48 < 56', + story: 'components-misc-progressspinner--sizes', + run: async ({ page, expect }) => { + const sizes = await page.locator('.p-progressspinner').evaluateAll((elements) => + elements.map((element) => Math.round(element.getBoundingClientRect().width)) + ); + expect(sizes.length, 'количество').toBe(4); + expect(sizes[0] < sizes[1] && sizes[1] < sizes[2] && sizes[2] < sizes[3], 'размеры возрастают').toBe(true); + } + }, + { + name: 'Default: role=progressbar и доступное имя', + story: 'components-misc-progressspinner--default', + run: async ({ page, expect }) => { + const spinner = page.locator('.p-progressspinner'); + expect(await spinner.getAttribute('role'), 'role').toBe('progressbar'); + expect(await spinner.getAttribute('aria-label'), 'aria-label').toBe('Загрузка'); + } + }, + { + name: 'Monochrome: класс монохромного режима', + story: 'components-misc-progressspinner--monochrome', + run: async ({ page, expect }) => { + const classes = await page.locator('.p-progressspinner').evaluateAll((elements) => elements.map((element) => element.className)); + expect(classes.length, 'количество').toBe(2); + expect(classes.every((className) => className.includes('p-progressspinner-monochrome')), 'все монохромные').toBe(true); + } + }, + ...STORIES.map(smoke), + { ...smoke(STORIES[0]), name: `Smoke: ${STORIES[0].name} (тёмная тема)`, theme: 'dark' } + ] +}; diff --git a/e2e/specs/radiobutton.e2e.mjs b/e2e/specs/radiobutton.e2e.mjs new file mode 100644 index 00000000..2d66deeb --- /dev/null +++ b/e2e/specs/radiobutton.e2e.mjs @@ -0,0 +1,91 @@ +/** + * E2E-спека RadioButton: выбор в группе, клавиатура, состояния и лейблы. + */ + +const STORIES = [ + { id: 'components-form-radiobutton--caption', name: 'Caption' }, + { id: 'components-form-radiobutton--default', name: 'Default' }, + { id: 'components-form-radiobutton--disabled', name: 'Disabled' }, + { id: 'components-form-radiobutton--group', name: 'Group' }, + { id: 'components-form-radiobutton--invalid', name: 'Invalid' }, + { id: 'components-form-radiobutton--label-position', name: 'LabelPosition' } +]; + +const smoke = (story) => ({ + name: `Smoke: ${story.name}`, + story: story.id, + run: async ({ page, expect, errors }) => { + expect(errors.filter((error) => error.type === 'pageerror').map((error) => error.text), 'ошибки страницы').toEqual([]); + expect(await page.locator('#storybook-root > *').count(), 'корень story').toBeGreaterThan(0); + const box = await page.locator('#storybook-root').boundingBox(); + expect(Boolean(box && box.width > 0), 'ширина story').toBe(true); + } +}); + +export default { + component: 'radiobutton', + stories: Object.fromEntries(STORIES.map((story) => [story.id, story.id])), + tests: [ + { + name: 'Group: две группы по два варианта, по одному выбору в каждой', + story: 'components-form-radiobutton--group', + run: async ({ page, expect }) => { + const inputs = page.locator('.p-radiobutton-input'); + expect(await inputs.count(), 'количество').toBe(4); + const names = await inputs.evaluateAll((elements) => [...new Set(elements.map((element) => element.name))]); + expect(names.length, 'количество групп').toBe(2); + + await page.locator('.p-radiobutton').nth(1).click(); + const checked = await inputs.evaluateAll((elements) => elements.map((element) => element.checked)); + expect(checked.filter(Boolean).length, 'по одному в каждой группе').toBe(2); + expect(checked[1], 'выбран второй в первой группе').toBe(true); + expect(checked[2], 'вторая группа не изменилась').toBe(true); + } + }, + { + name: 'Keyboard: стрелка переключает выбор в группе', + story: 'components-form-radiobutton--group', + run: async ({ page, expect }) => { + const inputs = page.locator('.p-radiobutton-input'); + await inputs.first().focus(); + await page.keyboard.press('ArrowDown'); + expect(await inputs.nth(1).isChecked(), 'выбран следующий').toBe(true); + expect(await inputs.first().isChecked(), 'первый снят').toBe(false); + } + }, + { + name: 'Disabled: поле отключено', + story: 'components-form-radiobutton--disabled', + run: async ({ page, expect }) => { + expect(await page.locator('.p-radiobutton-input').first().isDisabled(), 'disabled').toBe(true); + } + }, + { + name: 'Invalid: класс p-invalid на радиокнопке', + story: 'components-form-radiobutton--invalid', + run: async ({ page, expect }) => { + expect(await page.locator('.p-radiobutton').first().getAttribute('class'), 'invalid').toContain('p-invalid'); + } + }, + { + name: 'LabelPosition: лейбл связан с полем', + story: 'components-form-radiobutton--label-position', + run: async ({ page, expect }) => { + const label = page.locator('label').first(); + const inputId = await page.locator('.p-radiobutton-input').first().getAttribute('id'); + expect(await label.getAttribute('for'), 'for').toBe(inputId); + } + }, + { + name: 'RadioButton: tabindex не должен быть NaN', + story: 'components-form-radiobutton--default', + knownIssue: 'PrimeNG выставляет tabindex="NaN" на нативный input', + run: async ({ page, expect }) => { + const tabindex = await page.locator('.p-radiobutton-input').first().getAttribute('tabindex'); + expect(tabindex === null || /^-?\d+$/.test(tabindex), 'валидный tabindex').toBe(true); + } + }, + ...STORIES.map(smoke), + { ...smoke(STORIES[0]), name: `Smoke: ${STORIES[0].name} (тёмная тема)`, theme: 'dark' } + ] +}; diff --git a/e2e/specs/rating.e2e.mjs b/e2e/specs/rating.e2e.mjs new file mode 100644 index 00000000..680a563f --- /dev/null +++ b/e2e/specs/rating.e2e.mjs @@ -0,0 +1,69 @@ +/** + * E2E-спека Rating: звёзды, выбор, доступность радиогруппы и состояния. + */ + +const STORIES = [ + { id: 'components-form-rating--clearable', name: 'Clearable' }, + { id: 'components-form-rating--default', name: 'Default' }, + { id: 'components-form-rating--disabled', name: 'Disabled' }, + { id: 'components-form-rating--read-only', name: 'ReadOnly' } +]; + +const smoke = (story) => ({ + name: `Smoke: ${story.name}`, + story: story.id, + run: async ({ page, expect, errors }) => { + expect(errors.filter((error) => error.type === 'pageerror').map((error) => error.text), 'ошибки страницы').toEqual([]); + expect(await page.locator('#storybook-root > *').count(), 'корень story').toBeGreaterThan(0); + const box = await page.locator('#storybook-root').boundingBox(); + expect(Boolean(box && box.width > 0), 'ширина story').toBe(true); + } +}); + +export default { + component: 'rating', + stories: Object.fromEntries(STORIES.map((story) => [story.id, story.id])), + tests: [ + { + name: 'Default: три звезды и выбор четвёртой', + story: 'components-form-rating--default', + run: async ({ page, expect }) => { + expect(await page.locator('.p-rating-on-icon').count(), 'заполненные').toBe(3); + await page.locator('.p-rating-option').nth(3).click(); + expect(await page.locator('.p-rating-on-icon').count(), 'после клика').toBe(4); + } + }, + { + name: 'A11y: радиогруппа с именами звёзд', + story: 'components-form-rating--default', + run: async ({ page, expect }) => { + const radios = page.locator('.p-rating input[type=radio]'); + expect(await radios.count(), 'радио').toBe(5); + const names = await radios.evaluateAll((elements) => elements.map((element) => element.getAttribute('aria-label'))); + expect(names.filter(Boolean).length, 'имена звёзд').toBe(5); + } + }, + { + name: 'Disabled: клик не меняет оценку', + story: 'components-form-rating--disabled', + run: async ({ page, expect }) => { + const before = await page.locator('.p-rating-on-icon').count(); + await page.locator('.p-rating-option').last().click({ force: true }); + expect(await page.locator('.p-rating-on-icon').count(), 'оценка').toBe(before); + expect(await page.locator('.p-rating').getAttribute('class'), 'класс').toContain('p-disabled'); + } + }, + { + name: 'ReadOnly: клик не меняет оценку', + story: 'components-form-rating--read-only', + run: async ({ page, expect }) => { + const before = await page.locator('.p-rating-on-icon').count(); + await page.locator('.p-rating-option').last().click({ force: true }); + expect(await page.locator('.p-rating-on-icon').count(), 'оценка').toBe(before); + expect(await page.locator('.p-rating').getAttribute('class'), 'класс').toContain('p-readonly'); + } + }, + ...STORIES.map(smoke), + { ...smoke(STORIES[0]), name: `Smoke: ${STORIES[0].name} (тёмная тема)`, theme: 'dark' } + ] +}; diff --git a/e2e/specs/scroll-panel.e2e.mjs b/e2e/specs/scroll-panel.e2e.mjs new file mode 100644 index 00000000..082aad5b --- /dev/null +++ b/e2e/specs/scroll-panel.e2e.mjs @@ -0,0 +1,45 @@ +/** + * E2E-спека ScrollPanel: контент, прокрутка и ориентация. + */ + +const STORIES = [ + { id: 'components-panel-scrollpanel--both', name: 'Both' }, + { id: 'components-panel-scrollpanel--default', name: 'Default' }, + { id: 'components-panel-scrollpanel--horizontal', name: 'Horizontal' } +]; + +const smoke = (story) => ({ + name: `Smoke: ${story.name}`, + story: story.id, + run: async ({ page, expect, errors }) => { + expect(errors.filter((error) => error.type === 'pageerror').map((error) => error.text), 'ошибки страницы').toEqual([]); + expect(await page.locator('#storybook-root > *').count(), 'корень story').toBeGreaterThan(0); + const box = await page.locator('#storybook-root').boundingBox(); + expect(Boolean(box && box.width > 0), 'ширина story').toBe(true); + } +}); + +export default { + component: 'scroll-panel', + stories: Object.fromEntries(STORIES.map((story) => [story.id, story.id])), + tests: [ + { + name: 'Default: панель и её контент', + story: 'components-panel-scrollpanel--default', + run: async ({ page, expect }) => { + expect(await page.locator('.p-scrollpanel').count(), 'панель').toBe(1); + expect((await page.locator('#storybook-root').innerText()).length, 'контент').toBeGreaterThan(100); + } + }, + { + name: 'Horizontal: горизонтальная ориентация', + story: 'components-panel-scrollpanel--horizontal', + run: async ({ page, expect }) => { + const className = await page.locator('.p-scrollpanel').getAttribute('class'); + expect(className.includes('horizontal') || (await page.locator('.p-scrollpanel').boundingBox()).width > 0, 'панель').toBe(true); + } + }, + ...STORIES.map(smoke), + { ...smoke(STORIES[0]), name: `Smoke: ${STORIES[0].name} (тёмная тема)`, theme: 'dark' } + ] +}; diff --git a/e2e/specs/select-button.e2e.mjs b/e2e/specs/select-button.e2e.mjs new file mode 100644 index 00000000..dd10e1d7 --- /dev/null +++ b/e2e/specs/select-button.e2e.mjs @@ -0,0 +1,74 @@ +/** + * E2E-спека SelectButton: группа, выбор, disabled и иконки. + */ + +const STORIES = [ + { id: 'components-form-selectbutton--default', name: 'Default' }, + { id: 'components-form-selectbutton--disabled', name: 'Disabled' }, + { id: 'components-form-selectbutton--fluid', name: 'Fluid' }, + { id: 'components-form-selectbutton--selected', name: 'Selected' }, + { id: 'components-form-selectbutton--semi-disabled', name: 'Semi Disabled' }, + { id: 'components-form-selectbutton--with-icons', name: 'With Icons' } +]; + +const smoke = (story) => ({ + name: `Smoke: ${story.name}`, + story: story.id, + run: async ({ page, expect, errors }) => { + expect(errors.filter((error) => error.type === 'pageerror').map((error) => error.text), 'ошибки страницы').toEqual([]); + expect(await page.locator('#storybook-root > *').count(), 'корень story').toBeGreaterThan(0); + const box = await page.locator('#storybook-root').boundingBox(); + expect(Boolean(box && box.width > 0), 'ширина story').toBe(true); + } +}); + +export default { + component: 'select-button', + stories: Object.fromEntries(STORIES.map((story) => [story.id, story.id])), + tests: [ + { + name: 'Default: группа из трёх кнопок и переключение выбора', + story: 'components-form-selectbutton--default', + run: async ({ page, expect }) => { + expect(await page.locator('.p-selectbutton').getAttribute('role'), 'role').toBe('group'); + const buttons = page.locator('.p-selectbutton .p-togglebutton'); + expect(await buttons.count(), 'кнопки').toBe(3); + expect(await buttons.first().getAttribute('aria-pressed'), 'первая выбрана').toBe('true'); + + await buttons.nth(1).click(); + const pressed = await buttons.evaluateAll((elements) => elements.map((element) => element.getAttribute('aria-pressed'))); + expect(pressed, 'после клика').toEqual(['false', 'true', 'false']); + } + }, + { + name: 'Disabled: вся группа помечена p-disabled', + story: 'components-form-selectbutton--disabled', + run: async ({ page, expect }) => { + const classes = await page.locator('.p-selectbutton .p-togglebutton').evaluateAll((elements) => + elements.map((element) => element.className) + ); + expect(classes.every((className) => className.includes('p-disabled')), 'все p-disabled').toBe(true); + } + }, + { + name: 'Disabled: кнопки объявляют aria-disabled', + story: 'components-form-selectbutton--disabled', + knownIssue: 'p-togglebutton в disabled-группе имеет p-disabled, но не aria-disabled', + run: async ({ page, expect }) => { + const values = await page.locator('.p-selectbutton .p-togglebutton').evaluateAll((elements) => + elements.map((element) => element.getAttribute('aria-disabled')) + ); + expect(values.every((value) => value === 'true'), 'aria-disabled').toBe(true); + } + }, + { + name: 'With Icons: иконки в кнопках', + story: 'components-form-selectbutton--with-icons', + run: async ({ page, expect }) => { + expect(await page.locator('.p-selectbutton .ti').count(), 'иконки').toBeGreaterThan(0); + } + }, + ...STORIES.map(smoke), + { ...smoke(STORIES[0]), name: `Smoke: ${STORIES[0].name} (тёмная тема)`, theme: 'dark' } + ] +}; diff --git a/e2e/specs/select.e2e.mjs b/e2e/specs/select.e2e.mjs new file mode 100644 index 00000000..f6779e64 --- /dev/null +++ b/e2e/specs/select.e2e.mjs @@ -0,0 +1,347 @@ +/** + * E2E-спека Select: поведение, клавиатура, состояния и доступность. + * + * Тесты с пометкой `knownIssue` описывают ожидаемое поведение, которое сейчас + * не выполняется. Они не валят прогон, но попадают в отчёт — когда дефект + * починят, тест станет зелёным и отчёт это покажет. + */ + +const combo = (page) => page.locator('[role=combobox]').first(); +const overlay = (page) => page.locator('.p-select-overlay'); +const options = (page) => page.locator('.p-select-option'); + +const optionByText = (page, text) => page.locator('.p-select-option', { hasText: text }).first(); + +const openByClick = async (page) => { + await combo(page).click(); + await page.waitForSelector('.p-select-overlay', { state: 'visible' }); + // PrimeNG вешает document-listener и запускает анимацию уже после появления узла: + // клик в первые ~100ms может не закрыть список, хотя пользовательский клик — закроет. + await page.waitForTimeout(200); +}; + +const waitClosed = (page) => page.waitForSelector('.p-select-overlay', { state: 'detached' }); + +const a11yRulesWithoutDocumentNoise = { + 'landmark-one-main': { enabled: false }, + region: { enabled: false }, + 'page-has-heading-one': { enabled: false }, + 'scrollable-region-focusable': { enabled: false }, + 'color-contrast': { enabled: false } +}; + +export default { + component: 'select', + stories: { + default: 'components-form-select--default', + filter: 'components-form-select--filter', + grouped: 'components-form-select--grouped', + editable: 'components-form-select--editable', + sizes: 'components-form-select--sizes', + disabled: 'components-form-select--disabled', + labelPosition: 'components-form-select--label-position' + }, + tests: [ + { + name: 'Открытие по клику: оверлей, aria-expanded и все опции', + story: 'default', + run: async ({ page, expect }) => { + await openByClick(page); + + expect(await overlay(page).isVisible(), 'оверлей').toBe(true); + expect(await page.locator('#storybook-root .p-select-overlay').count(), 'оверлей вне story-root').toBe(0); + expect(await page.locator('body .p-select-overlay').count(), 'оверлей в body').toBe(1); + expect(await combo(page).getAttribute('aria-expanded'), 'aria-expanded').toBe('true'); + expect(await options(page).count(), 'количество опций').toBe(5); + expect(await page.locator('.p-select-list[role=listbox]').count(), 'listbox').toBe(1); + expect(await page.locator('.p-select-option[role=option]').count(), 'role=option').toBe(5); + } + }, + { + name: 'Выбор опции: значение, aria-label, иконка очистки', + story: 'default', + run: async ({ page, expect }) => { + await openByClick(page); + await optionByText(page, 'Москва').click(); + await waitClosed(page); + + expect(await page.locator('.p-select-label').innerText(), 'текст поля').toBe('Москва'); + expect(await combo(page).getAttribute('aria-label'), 'aria-label поля').toBe('Москва'); + expect(await combo(page).getAttribute('aria-expanded'), 'aria-expanded').toBe('false'); + expect(await page.locator('.p-select-clear-icon').count(), 'иконка очистки').toBe(1); + expect(await overlay(page).count(), 'оверлей после выбора').toBe(0); + } + }, + { + name: 'Очистка: плейсхолдер возвращается, иконка исчезает', + story: 'default', + run: async ({ page, expect }) => { + await openByClick(page); + await optionByText(page, 'Казань').click(); + await waitClosed(page); + + await page.locator('.p-select-clear-icon').click(); + await ctxWait(page, async () => (await page.locator('.p-select-clear-icon').count()) === 0, 'иконка очистки исчезла'); + + expect(await page.locator('.p-select-label').innerText(), 'текст поля').toBe('Выберите город...'); + expect(await page.locator('.p-select-label.p-placeholder').count(), 'класс placeholder').toBe(1); + expect(await overlay(page).count(), 'оверлей').toBe(0); + } + }, + { + name: 'Клавиатура: ArrowDown открывает, Enter выбирает', + story: 'default', + run: async ({ page, expect }) => { + await combo(page).focus(); + await page.keyboard.press('ArrowDown'); + await page.waitForSelector('.p-select-overlay', { state: 'visible' }); + await page.keyboard.press('ArrowDown'); + + const firstActive = await combo(page).getAttribute('aria-activedescendant'); + await page.keyboard.press('ArrowDown'); + const secondActive = await combo(page).getAttribute('aria-activedescendant'); + + expect(firstActive, 'первый активный пункт').toBeTruthy(); + expect(secondActive !== firstActive, 'активный пункт сместился').toBe(true); + + await page.keyboard.press('Enter'); + await waitClosed(page); + + expect(await page.locator('.p-select-label').innerText(), 'выбранное значение').toBe('Москва'); + expect(await page.evaluate(() => document.activeElement?.getAttribute('role')), 'фокус после выбора').toBe('combobox'); + } + }, + { + name: 'Esc закрывает список и оставляет фокус на поле', + story: 'default', + run: async ({ page, expect }) => { + await combo(page).focus(); + await page.keyboard.press('ArrowDown'); + await page.waitForSelector('.p-select-overlay', { state: 'visible' }); + + await page.keyboard.press('Escape'); + await waitClosed(page); + + expect(await page.evaluate(() => document.activeElement?.getAttribute('role')), 'фокус после Esc').toBe('combobox'); + expect(await page.locator('.p-select-label').innerText(), 'значение не изменилось').toBe('Выберите город...'); + } + }, + { + name: 'Клик вне закрывает список без выбора', + story: 'default', + run: async ({ page, expect }) => { + await openByClick(page); + await page.mouse.click(600, 600); + await waitClosed(page); + + expect(await combo(page).getAttribute('aria-expanded'), 'aria-expanded').toBe('false'); + expect(await page.locator('.p-select-label').innerText(), 'значение').toBe('Выберите город...'); + } + }, + { + name: 'Фильтр оставляет только совпадающие опции и выбирает их', + story: 'filter', + run: async ({ page, expect, wait }) => { + await openByClick(page); + const filter = page.locator('.p-select-overlay input.p-select-filter'); + expect(await filter.count(), 'поле фильтра').toBe(1); + + await filter.fill('Мос'); + await wait(async () => (await options(page).count()) === 1); + + expect(await options(page).first().innerText(), 'единственная опция').toBe('Москва'); + + await options(page).first().click(); + await waitClosed(page); + expect(await page.locator('.p-select-label').innerText(), 'выбранное значение').toBe('Москва'); + } + }, + { + name: 'Фильтр сбрасывается при повторном открытии', + story: 'filter', + knownIssue: 'PrimeNG сохраняет введённый фильтр: после закрытия и открытия список остаётся отфильтрованным', + run: async ({ page, expect }) => { + await openByClick(page); + await page.locator('.p-select-overlay input.p-select-filter').fill('Мос'); + await page.keyboard.press('Escape'); + await waitClosed(page); + + await openByClick(page); + expect(await page.locator('.p-select-overlay input.p-select-filter').inputValue(), 'значение фильтра после reopen').toBe(''); + expect(await options(page).count(), 'количество опций после reopen').toBe(5); + } + }, + { + name: 'Disabled: не открывается, aria-disabled и tabindex=-1', + story: 'disabled', + run: async ({ page, expect }) => { + expect(await page.locator('.p-select.p-disabled').count(), 'класс p-disabled').toBe(1); + expect(await combo(page).getAttribute('aria-disabled'), 'aria-disabled').toBe('true'); + expect(await combo(page).getAttribute('tabindex'), 'tabindex').toBe('-1'); + + await combo(page).click({ force: true }); + await page.waitForTimeout(300); + expect(await overlay(page).count(), 'оверлей после клика').toBe(0); + + await page.keyboard.press('Tab'); + const roleAfterTab = await page.evaluate(() => document.activeElement?.getAttribute('role')); + expect(roleAfterTab !== 'combobox', 'disabled-поле не получает фокус по Tab').toBe(true); + } + }, + { + name: 'Grouped: заголовок группы не выбирается, опция выбирается', + story: 'grouped', + run: async ({ page, expect }) => { + await openByClick(page); + expect(await page.locator('.p-select-option-group').count(), 'заголовки групп').toBe(2); + + await page.locator('.p-select-option-group', { hasText: 'Германия' }).click(); + await page.waitForTimeout(200); + expect(await overlay(page).count(), 'оверлей после клика по заголовку').toBe(1); + expect(await page.locator('.p-select-label').innerText(), 'значение после клика по заголовку').toBe('Выберите город...'); + + await page.locator('.p-select-option', { hasText: 'Берлин' }).click(); + await waitClosed(page); + expect(await page.locator('.p-select-label').innerText(), 'выбранное значение').toBe('Берлин'); + } + }, + { + name: 'Grouped: заголовки групп не объявляются опциями', + story: 'grouped', + knownIssue: 'PrimeNG рендерит заголовки групп как role=option без aria-selected: скринридер считает их выбираемыми', + run: async ({ page, expect }) => { + await openByClick(page); + const roles = await page.locator('.p-select-option-group').evaluateAll((elements) => + elements.map((element) => element.getAttribute('role')) + ); + expect(roles, 'роли заголовков групп').toEqual(['presentation', 'presentation']); + } + }, + { + name: 'Label: клик по лейблу фокусирует поле, имя поля — текст лейбла', + story: 'labelPosition', + knownIssue: 'label for указывает на span, а не на labelable-элемент; у combobox нет aria-labelledby, доступное имя — плейсхолдер', + run: async ({ page, expect }) => { + const firstLabel = page.locator('label.extra-select-label').first(); + await firstLabel.click(); + await page.waitForTimeout(100); + + expect(await page.evaluate(() => document.activeElement?.getAttribute('role')), 'фокус после клика по лейблу').toBe('combobox'); + + const labelledBy = await combo(page).getAttribute('aria-labelledby'); + const ariaLabel = await combo(page).getAttribute('aria-label'); + expect(labelledBy !== null || ariaLabel === 'Город', 'доступное имя поля').toBe(true); + } + }, + { + name: 'Размеры small/base/large различаются высотой', + story: 'sizes', + knownIssue: 'components.select.root.sm и .lg в tokens.json равны base (fontSize.300, space.400), поэтому small/base/large — 46px', + run: async ({ page, expect }) => { + const heights = await page + .locator('.p-select') + .evaluateAll((elements) => elements.map((element) => Math.round(element.getBoundingClientRect().height))); + + expect(heights.length, 'количество селектов').toBe(4); + expect(heights[0] < heights[1], 'small ниже base').toBe(true); + expect(heights[1] < heights[2], 'base ниже large').toBe(true); + expect(heights[2] < heights[3], 'large ниже xlarge').toBe(true); + } + }, + { + name: 'Editable: поле ввода объявлено combobox с aria-expanded', + story: 'editable', + knownIssue: 'В editable-режиме PrimeNG рендерит input без role=combobox и aria-expanded', + run: async ({ page, expect }) => { + const input = page.locator('input.p-select-label').first(); + expect(await input.count(), 'поле ввода').toBe(1); + + expect(await input.getAttribute('role'), 'role поля').toBe('combobox'); + expect(await input.getAttribute('aria-expanded'), 'aria-expanded поля').toBe('false'); + } + }, + { + name: 'Клавиатурный фокус виден на поле', + story: 'default', + knownIssue: 'Фокус-кольцо выключено токеном select.root.focusRing.style = none, outline тоже none', + run: async ({ page, expect }) => { + await page.keyboard.press('Tab'); + const styles = await combo(page).evaluate((element) => { + const computed = getComputedStyle(element); + return { + outline: `${computed.outlineStyle} ${computed.outlineWidth}`, + boxShadow: computed.boxShadow + }; + }); + + const visible = styles.boxShadow !== 'none' || !styles.outline.startsWith('none'); + expect(visible, 'видимый индикатор фокуса').toBe(true); + } + }, + { + name: 'Оверлей не уже поля и не выходит за вьюпорт', + story: 'default', + run: async ({ page, expect }) => { + await openByClick(page); + const field = await page.locator('.p-select').boundingBox(); + const list = await overlay(page).boundingBox(); + const viewport = page.viewportSize(); + + expect(list.width >= field.width - 1, 'ширина оверлея').toBe(true); + expect(list.x >= 0, 'левый край').toBe(true); + expect(list.x + list.width <= viewport.width + 1, 'правый край').toBe(true); + } + }, + { + name: 'A11y: структура открытого списка без critical/serious', + story: 'default', + run: async ({ page, expect, a11y, formatViolations }) => { + await openByClick(page); + const violations = await a11y({ rules: a11yRulesWithoutDocumentNoise }); + expect(violations, `нарушения axe: ${formatViolations(violations)}`).toEqual([]); + } + }, + { + name: 'A11y: контраст текста поля в открытом списке', + story: 'default', + knownIssue: 'axe color-contrast: плейсхолдер поля не достигает 4.5:1', + run: async ({ page, expect, a11y, formatViolations }) => { + await openByClick(page); + const violations = await a11y({ + rules: { + 'landmark-one-main': { enabled: false }, + region: { enabled: false }, + 'page-has-heading-one': { enabled: false }, + 'scrollable-region-focusable': { enabled: false } + } + }); + expect(violations, `нарушения axe: ${formatViolations(violations)}`).toEqual([]); + } + }, + { + name: 'Тёмная тема: выбор значения и очистка работают', + story: 'default', + theme: 'dark', + run: async ({ page, expect }) => { + await openByClick(page); + await optionByText(page, 'Екатеринбург').click(); + await waitClosed(page); + + expect(await page.locator('.p-select-label').innerText(), 'значение').toBe('Екатеринбург'); + await page.locator('.p-select-clear-icon').click(); + await page.waitForTimeout(200); + expect(await page.locator('.p-select-label').innerText(), 'значение после очистки').toBe('Выберите город...'); + } + } + ] +}; + +/** Локальный wait для случая, когда нужен только предикат без ctx.wait. */ +async function ctxWait(page, predicate, label) { + const started = Date.now(); + while (Date.now() - started < 3000) { + if (await predicate()) return; + await page.waitForTimeout(50); + } + throw new Error(`${label}: не дождались за 3000ms`); +} diff --git a/e2e/specs/skeleton.e2e.mjs b/e2e/specs/skeleton.e2e.mjs new file mode 100644 index 00000000..177d79bc --- /dev/null +++ b/e2e/specs/skeleton.e2e.mjs @@ -0,0 +1,71 @@ +/** + * E2E-спека Skeleton: формы, размеры и отключение анимации. + */ + +const STORIES = [ + { id: 'components-misc-skeleton--card-placeholder', name: 'CardPlaceholder' }, + { id: 'components-misc-skeleton--circle', name: 'Circle' }, + { id: 'components-misc-skeleton--default', name: 'Default' }, + { id: 'components-misc-skeleton--no-animation', name: 'NoAnimation' }, + { id: 'components-misc-skeleton--rectangles', name: 'Rectangles' } +]; + +const smoke = (story) => ({ + name: `Smoke: ${story.name}`, + story: story.id, + run: async ({ page, expect, errors }) => { + expect(errors.filter((error) => error.type === 'pageerror').map((error) => error.text), 'ошибки страницы').toEqual([]); + expect(await page.locator('#storybook-root > *').count(), 'корень story').toBeGreaterThan(0); + const box = await page.locator('#storybook-root').boundingBox(); + expect(Boolean(box && box.width > 0), 'ширина story').toBe(true); + } +}); + +export default { + component: 'skeleton', + stories: Object.fromEntries(STORIES.map((story) => [story.id, story.id])), + tests: [ + { + name: 'Default: ширина контейнера и высота строки', + story: 'components-misc-skeleton--default', + run: async ({ page, expect }) => { + const box = await page.locator('.p-skeleton').first().boundingBox(); + expect(Math.round(box.width), 'ширина').toBeGreaterThan(1000); + expect(Math.round(box.height), 'высота').toBe(16); + } + }, + { + name: 'Circle: три круга с равными сторонами', + story: 'components-misc-skeleton--circle', + run: async ({ page, expect }) => { + const boxes = await page.locator('.p-skeleton-circle').evaluateAll((elements) => + elements.map((element) => { + const box = element.getBoundingClientRect(); + return { width: Math.round(box.width), height: Math.round(box.height) }; + }) + ); + expect(boxes.length, 'количество кругов').toBe(3); + for (const box of boxes) expect(box.width, 'круг').toBe(box.height); + expect(boxes[0].width < boxes[2].width, 'размеры различаются').toBe(true); + } + }, + { + name: 'Rectangles: несколько прямоугольников', + story: 'components-misc-skeleton--rectangles', + run: async ({ page, expect }) => { + expect(await page.locator('.p-skeleton').count(), 'количество').toBeGreaterThanOrEqual(3); + } + }, + { + name: 'NoAnimation: анимация отключена', + story: 'components-misc-skeleton--no-animation', + run: async ({ page, expect }) => { + const skeleton = page.locator('.p-skeleton').first(); + expect(await skeleton.getAttribute('class'), 'класс').toContain('p-skeleton-animation-none'); + expect(await skeleton.evaluate((element) => getComputedStyle(element).animationName), 'animation-name').toBe('none'); + } + }, + ...STORIES.map(smoke), + { ...smoke(STORIES[0]), name: `Smoke: ${STORIES[0].name} (тёмная тема)`, theme: 'dark' } + ] +}; diff --git a/e2e/specs/slider.e2e.mjs b/e2e/specs/slider.e2e.mjs new file mode 100644 index 00000000..2eb17a4b --- /dev/null +++ b/e2e/specs/slider.e2e.mjs @@ -0,0 +1,74 @@ +/** + * E2E-спека Slider: значения, диапазон, клавиатура и ориентация. + */ + +const STORIES = [ + { id: 'components-form-slider--default', name: 'Default' }, + { id: 'components-form-slider--disabled', name: 'Disabled' }, + { id: 'components-form-slider--range', name: 'Range' }, + { id: 'components-form-slider--step', name: 'Step' }, + { id: 'components-form-slider--vertical', name: 'Vertical' } +]; + +const smoke = (story) => ({ + name: `Smoke: ${story.name}`, + story: story.id, + run: async ({ page, expect, errors }) => { + expect(errors.filter((error) => error.type === 'pageerror').map((error) => error.text), 'ошибки страницы').toEqual([]); + expect(await page.locator('#storybook-root > *').count(), 'корень story').toBeGreaterThan(0); + const box = await page.locator('#storybook-root').boundingBox(); + expect(Boolean(box && box.width > 0), 'ширина story').toBe(true); + } +}); + +export default { + component: 'slider', + stories: Object.fromEntries(STORIES.map((story) => [story.id, story.id])), + tests: [ + { + name: 'Default: роль slider, 50 и стрелка вправо', + story: 'components-form-slider--default', + run: async ({ page, expect }) => { + const handle = page.locator('.p-slider-handle'); + expect(await handle.getAttribute('role'), 'role').toBe('slider'); + expect(await handle.getAttribute('aria-valuenow'), 'значение').toBe('50'); + expect(await handle.getAttribute('aria-valuemin'), 'min').toBe('0'); + expect(await handle.getAttribute('aria-valuemax'), 'max').toBe('100'); + + await handle.focus(); + await page.keyboard.press('ArrowRight'); + expect(await handle.getAttribute('aria-valuenow'), 'после ArrowRight').toBe('51'); + } + }, + { + name: 'Range: два ползунка 20 и 80', + story: 'components-form-slider--range', + run: async ({ page, expect }) => { + const handles = page.locator('.p-slider-handle'); + expect(await handles.count(), 'ползунки').toBe(2); + expect(await handles.nth(0).getAttribute('aria-valuenow'), 'первый').toBe('20'); + expect(await handles.nth(1).getAttribute('aria-valuenow'), 'второй').toBe('80'); + } + }, + { + name: 'Vertical: вертикальная ориентация', + story: 'components-form-slider--vertical', + run: async ({ page, expect }) => { + expect(await page.locator('.p-slider').getAttribute('class'), 'класс').toContain('p-slider-vertical'); + } + }, + { + name: 'Disabled: ползунок недоступен', + story: 'components-form-slider--disabled', + knownIssue: 'У disabled-слайдера handle остаётся focusable (tabindex=0) и без aria-disabled', + run: async ({ page, expect }) => { + const handle = page.locator('.p-slider-handle'); + const tabindex = await handle.getAttribute('tabindex'); + const disabled = await handle.getAttribute('aria-disabled'); + expect(disabled === 'true' || tabindex === '-1', 'недоступен').toBe(true); + } + }, + ...STORIES.map(smoke), + { ...smoke(STORIES[0]), name: `Smoke: ${STORIES[0].name} (тёмная тема)`, theme: 'dark' } + ] +}; diff --git a/e2e/specs/stepper.e2e.mjs b/e2e/specs/stepper.e2e.mjs new file mode 100644 index 00000000..c0d952f1 --- /dev/null +++ b/e2e/specs/stepper.e2e.mjs @@ -0,0 +1,79 @@ +/** + * E2E-спека Stepper: шаги, переходы, вертикальная ориентация и состояния. + */ + +const STORIES = [ + { id: 'components-panel-stepper--default', name: 'Default' }, + { id: 'components-panel-stepper--linear', name: 'Linear' }, + { id: 'components-panel-stepper--states', name: 'States' }, + { id: 'components-panel-stepper--vertical', name: 'Vertical' } +]; + +const smoke = (story) => ({ + name: `Smoke: ${story.name}`, + story: story.id, + run: async ({ page, expect, errors }) => { + expect(errors.filter((error) => error.type === 'pageerror').map((error) => error.text), 'ошибки страницы').toEqual([]); + expect(await page.locator('#storybook-root > *').count(), 'корень story').toBeGreaterThan(0); + const box = await page.locator('#storybook-root').boundingBox(); + expect(Boolean(box && box.width > 0), 'ширина story').toBe(true); + } +}); + +const panelText = (page) => page.locator('.p-stepper-panel, .p-step-panel').innerText(); + +export default { + component: 'stepper', + stories: Object.fromEntries(STORIES.map((story) => [story.id, story.id])), + tests: [ + { + name: 'Default: три шага и переход Вперёд/Назад', + story: 'components-panel-stepper--default', + run: async ({ page, expect }) => { + expect(await page.locator('.p-stepper').getAttribute('role'), 'role').toBe('tablist'); + expect(await page.locator('.p-step-header').count(), 'шаги').toBe(3); + expect(await page.locator('#storybook-root').innerText(), 'первый шаг').toContain('Шаг 1'); + + await page.locator('button.p-button', { hasText: 'Вперёд' }).click(); + expect(await page.locator('#storybook-root').innerText(), 'после Вперёд').toContain('Шаг 2'); + + await page.locator('button.p-button', { hasText: 'Назад' }).click(); + expect(await page.locator('#storybook-root').innerText(), 'после Назад').toContain('Шаг 1'); + } + }, + { + name: 'Default: клик по третьему шагу открывает его', + story: 'components-panel-stepper--default', + run: async ({ page, expect }) => { + await page.locator('.p-step-header').nth(2).click(); + expect(await page.locator('#storybook-root').innerText(), 'активный шаг').toContain('Шаг 3'); + } + }, + { + name: 'Vertical: шаги стоят друг под другом', + story: 'components-panel-stepper--vertical', + run: async ({ page, expect }) => { + const boxes = await page.locator('.p-step-header').evaluateAll((headers) => + headers.map((header) => { + const box = header.getBoundingClientRect(); + return { x: Math.round(box.x), y: Math.round(box.y) }; + }) + ); + expect(boxes.length, 'шаги').toBe(3); + expect(new Set(boxes.map((box) => box.x)).size, 'одна колонка').toBe(1); + expect(boxes[0].y < boxes[1].y && boxes[1].y < boxes[2].y, 'шаги друг под другом').toBe(true); + } + }, + { + name: 'States: подписи готово/ошибка/недоступно', + story: 'components-panel-stepper--states', + run: async ({ page, expect }) => { + const text = await page.locator('#storybook-root').innerText(); + expect(text, 'статусы').toContain('ошибка'); + expect(text, 'недоступный шаг').toContain('недоступно'); + } + }, + ...STORIES.map(smoke), + { ...smoke(STORIES[0]), name: `Smoke: ${STORIES[0].name} (тёмная тема)`, theme: 'dark' } + ] +}; diff --git a/e2e/specs/tabs.e2e.mjs b/e2e/specs/tabs.e2e.mjs new file mode 100644 index 00000000..93051f57 --- /dev/null +++ b/e2e/specs/tabs.e2e.mjs @@ -0,0 +1,62 @@ +/** + * E2E-спека Tabs: роли, переключение, disabled и клавиатура. + */ + +const STORIES = [ + { id: 'components-menu-tabs--default', name: 'Default' }, + { id: 'components-menu-tabs--with-badge', name: 'WithBadge' }, + { id: 'components-menu-tabs--with-disabled', name: 'WithDisabled' } +]; + +const smoke = (story) => ({ + name: `Smoke: ${story.name}`, + story: story.id, + run: async ({ page, expect, errors }) => { + expect(errors.filter((error) => error.type === 'pageerror').map((error) => error.text), 'ошибки страницы').toEqual([]); + expect(await page.locator('#storybook-root > *').count(), 'корень story').toBeGreaterThan(0); + const box = await page.locator('#storybook-root').boundingBox(); + expect(Boolean(box && box.width > 0), 'ширина story').toBe(true); + } +}); + +export default { + component: 'tabs', + stories: Object.fromEntries(STORIES.map((story) => [story.id, story.id])), + tests: [ + { + name: 'Default: три вкладки и переключение', + story: 'components-menu-tabs--default', + run: async ({ page, expect }) => { + const tabs = page.locator('.p-tab'); + expect(await tabs.count(), 'вкладки').toBe(3); + expect(await tabs.first().getAttribute('role'), 'role').toBe('tab'); + expect(await page.locator('.p-tab-active').innerText(), 'активная').toBe('Профиль'); + + await tabs.nth(1).click(); + expect(await page.locator('.p-tab-active').innerText(), 'после клика').toBe('Настройки'); + expect(await page.locator('.p-tabpanel-active').innerText(), 'панель').toBe('Параметры аккаунта'); + } + }, + { + name: 'WithDisabled: недоступная вкладка не активируется', + story: 'components-menu-tabs--with-disabled', + run: async ({ page, expect }) => { + const disabled = page.locator('.p-tab.p-disabled, .p-tab[aria-disabled=true]'); + expect(await disabled.count(), 'disabled-вкладка').toBe(1); + expect((await page.locator('.p-tab-active').innerText()) !== 'Недоступно', 'активная не disabled').toBe(true); + } + }, + { + name: 'Keyboard: стрелка переключает вкладку', + story: 'components-menu-tabs--default', + knownIssue: 'ArrowRight не переключает вкладку: активной остаётся первая', + run: async ({ page, expect }) => { + await page.locator('.p-tab').first().focus(); + await page.keyboard.press('ArrowRight'); + expect(await page.locator('.p-tab-active').innerText(), 'после ArrowRight').toBe('Настройки'); + } + }, + ...STORIES.map(smoke), + { ...smoke(STORIES[0]), name: `Smoke: ${STORIES[0].name} (тёмная тема)`, theme: 'dark' } + ] +}; diff --git a/e2e/specs/tag.e2e.mjs b/e2e/specs/tag.e2e.mjs new file mode 100644 index 00000000..fbd2fb47 --- /dev/null +++ b/e2e/specs/tag.e2e.mjs @@ -0,0 +1,64 @@ +/** + * E2E-спека Tag: severity, скругление и иконка. + */ + +const STORIES = [ + { id: 'components-misc-tag--default', name: 'Primary' }, + { id: 'components-misc-tag--rounded', name: 'Rounded' }, + { id: 'components-misc-tag--severity', name: 'Severity' }, + { id: 'components-misc-tag--with-icon', name: 'WithIcon' } +]; + +const smoke = (story) => ({ + name: `Smoke: ${story.name}`, + story: story.id, + run: async ({ page, expect, errors }) => { + expect(errors.filter((error) => error.type === 'pageerror').map((error) => error.text), 'ошибки страницы').toEqual([]); + expect(await page.locator('#storybook-root > *').count(), 'корень story').toBeGreaterThan(0); + const box = await page.locator('#storybook-root').boundingBox(); + expect(Boolean(box && box.width > 0), 'ширина story').toBe(true); + } +}); + +export default { + component: 'tag', + stories: Object.fromEntries(STORIES.map((story) => [story.id, story.id])), + tests: [ + { + name: 'Severity: классы шести severity', + story: 'components-misc-tag--severity', + run: async ({ page, expect }) => { + const classes = await page.locator('.p-tag').evaluateAll((elements) => elements.map((element) => element.className)); + expect(classes.length, 'количество тегов').toBe(12); + expect(classes[1], 'secondary').toContain('p-tag-secondary'); + expect(classes[2], 'info').toContain('p-tag-info'); + expect(classes[3], 'success').toContain('p-tag-success'); + expect(classes[4], 'warn').toContain('p-tag-warn'); + expect(classes[5], 'danger').toContain('p-tag-danger'); + } + }, + { + name: 'Rounded: шесть скруглённых тегов', + story: 'components-misc-tag--rounded', + run: async ({ page, expect }) => { + expect(await page.locator('.p-tag.p-tag-rounded').count(), 'скруглённые').toBeGreaterThanOrEqual(6); + } + }, + { + name: 'WithIcon: иконка внутри тега', + story: 'components-misc-tag--with-icon', + run: async ({ page, expect }) => { + expect(await page.locator('.p-tag .ti').count(), 'иконки').toBeGreaterThan(0); + } + }, + { + name: 'Primary: текст тега', + story: 'components-misc-tag--default', + run: async ({ page, expect }) => { + expect(await page.locator('.p-tag').innerText(), 'текст').toBe('Tag'); + } + }, + ...STORIES.map(smoke), + { ...smoke(STORIES[0]), name: `Smoke: ${STORIES[0].name} (тёмная тема)`, theme: 'dark' } + ] +}; diff --git a/e2e/specs/textarea.e2e.mjs b/e2e/specs/textarea.e2e.mjs new file mode 100644 index 00000000..c5585bdc --- /dev/null +++ b/e2e/specs/textarea.e2e.mjs @@ -0,0 +1,116 @@ +/** + * E2E-спека Textarea: ввод, лейблы, размеры, валидация и disabled. + */ + +const STORIES = [ + { id: 'components-form-textarea--auto-resize', name: 'AutoResize' }, + { id: 'components-form-textarea--default', name: 'Default' }, + { id: 'components-form-textarea--disabled', name: 'Disabled' }, + { id: 'components-form-textarea--float-label', name: 'FloatLabel' }, + { id: 'components-form-textarea--invalid', name: 'Invalid' }, + { id: 'components-form-textarea--labels', name: 'Labels' }, + { id: 'components-form-textarea--readonly', name: 'Readonly' }, + { id: 'components-form-textarea--sizes', name: 'Sizes' } +]; + +const smoke = (story) => ({ + name: `Smoke: ${story.name}`, + story: story.id, + run: async ({ page, expect, errors }) => { + expect(errors.filter((error) => error.type === 'pageerror').map((error) => error.text), 'ошибки страницы').toEqual([]); + expect(await page.locator('#storybook-root > *').count(), 'корень story').toBeGreaterThan(0); + const box = await page.locator('#storybook-root').boundingBox(); + expect(Boolean(box && box.width > 0), 'ширина story').toBe(true); + } +}); + +export default { + component: 'textarea', + stories: Object.fromEntries(STORIES.map((story) => [story.id, story.id])), + tests: [ + { + name: 'Default: ввод и связь с лейблом', + story: 'components-form-textarea--default', + run: async ({ page, expect }) => { + const textarea = page.locator('textarea'); + expect(await page.locator('label').getAttribute('for'), 'for').toBe(await textarea.getAttribute('id')); + + await textarea.fill('Комментарий к заказу'); + expect(await textarea.inputValue(), 'значение').toBe('Комментарий к заказу'); + expect(await textarea.getAttribute('class'), 'p-filled').toContain('p-filled'); + } + }, + { + name: 'Invalid: класс p-invalid', + story: 'components-form-textarea--invalid', + run: async ({ page, expect }) => { + expect(await page.locator('textarea').getAttribute('class'), 'invalid').toContain('p-invalid'); + } + }, + { + name: 'Invalid: поле объявляет aria-invalid', + story: 'components-form-textarea--invalid', + knownIssue: 'PrimeNG ставит только класс p-invalid; aria-invalid на textarea отсутствует', + run: async ({ page, expect }) => { + expect(await page.locator('textarea').getAttribute('aria-invalid'), 'aria-invalid').toBe('true'); + } + }, + { + name: 'Readonly: текст нельзя изменить', + story: 'components-form-textarea--readonly', + run: async ({ page, expect }) => { + const textarea = page.locator('textarea'); + expect(await textarea.evaluate((element) => element.readOnly), 'readonly').toBe(true); + } + }, + { + name: 'Disabled: поле нельзя изменить', + story: 'components-form-textarea--disabled', + knownIssue: 'FormControl.disable() не доходит до textarea: disabled=false, ввод меняет значение', + run: async ({ page, expect }) => { + const textarea = page.locator('textarea'); + const before = await textarea.inputValue(); + await textarea.fill('попытка ввода').catch(() => undefined); + expect(await textarea.inputValue(), 'значение не изменилось').toBe(before); + expect(await textarea.evaluate((element) => element.disabled), 'disabled').toBe(true); + } + }, + { + name: 'AutoResize: поле растёт при вводе', + story: 'components-form-textarea--auto-resize', + run: async ({ page, expect, wait }) => { + const textarea = page.locator('textarea'); + const before = (await textarea.boundingBox()).height; + await textarea.fill('Строка 1\nСтрока 2\nСтрока 3\nСтрока 4\nСтрока 5\nСтрока 6'); + await wait(async () => (await textarea.boundingBox()).height > before); + expect((await textarea.boundingBox()).height > before, 'высота выросла').toBe(true); + } + }, + { + name: 'Sizes: small получает класс p-textarea-sm', + story: { id: 'components-form-textarea--sizes', args: 'size:small' }, + run: async ({ page, expect }) => { + const textarea = page.locator('textarea'); + expect(await textarea.getAttribute('class'), 'класс sm').toContain('p-textarea-sm'); + } + }, + { + name: 'Sizes: large получает класс p-textarea-lg', + story: { id: 'components-form-textarea--sizes', args: 'size:large' }, + run: async ({ page, expect }) => { + expect(await page.locator('textarea').getAttribute('class'), 'класс lg').toContain('p-textarea-lg'); + } + }, + { + name: 'Sizes: xlarge выше base', + story: { id: 'components-form-textarea--sizes', args: 'size:xlarge' }, + run: async ({ page, expect }) => { + const textarea = page.locator('textarea'); + expect(await textarea.getAttribute('class'), 'класс xlg').toContain('p-textarea-xlg'); + expect((await textarea.boundingBox()).height, 'высота xlg').toBeGreaterThan(80); + } + }, + ...STORIES.map(smoke), + { ...smoke(STORIES[0]), name: `Smoke: ${STORIES[0].name} (тёмная тема)`, theme: 'dark' } + ] +}; diff --git a/e2e/specs/tieredmenu.e2e.mjs b/e2e/specs/tieredmenu.e2e.mjs new file mode 100644 index 00000000..657e22f7 --- /dev/null +++ b/e2e/specs/tieredmenu.e2e.mjs @@ -0,0 +1,58 @@ +/** + * E2E-спека TieredMenu: пункты, вложенные подменю и выбранный пункт. + */ + +const STORIES = [ + { id: 'components-menu-tieredmenu--basic', name: 'Basic' }, + { id: 'components-menu-tieredmenu--custom', name: 'Custom' }, + { id: 'components-menu-tieredmenu--with-selected', name: 'WithSelected' } +]; + +const smoke = (story) => ({ + name: `Smoke: ${story.name}`, + story: story.id, + run: async ({ page, expect, errors }) => { + expect(errors.filter((error) => error.type === 'pageerror').map((error) => error.text), 'ошибки страницы').toEqual([]); + expect(await page.locator('#storybook-root > *').count(), 'корень story').toBeGreaterThan(0); + const box = await page.locator('#storybook-root').boundingBox(); + expect(Boolean(box && box.width > 0), 'ширина story').toBe(true); + } +}); + +export default { + component: 'tieredmenu', + stories: Object.fromEntries(STORIES.map((story) => [story.id, story.id])), + tests: [ + { + name: 'Basic: корневые пункты с ролью menuitem', + story: 'components-menu-tieredmenu--basic', + run: async ({ page, expect }) => { + const items = page.locator('.p-tieredmenu-root-list > .p-tieredmenu-item'); + expect(await items.count(), 'корневые пункты').toBeGreaterThanOrEqual(3); + expect(await items.first().getAttribute('role'), 'role').toBe('menuitem'); + } + }, + { + name: 'Basic: пункт открывает вложенное подменю', + story: 'components-menu-tieredmenu--basic', + run: async ({ page, expect }) => { + const first = page.locator('.p-tieredmenu-root-list > .p-tieredmenu-item').first(); + await first.locator('a').first().click(); + await page.waitForSelector('.p-tieredmenu-submenu', { state: 'visible' }); + expect(await first.getAttribute('aria-expanded'), 'aria-expanded').toBe('true'); + expect(await page.locator('.p-tieredmenu-submenu').first().isVisible(), 'подменю').toBe(true); + } + }, + { + name: 'WithSelected: три пункта и выбранный класс', + story: 'components-menu-tieredmenu--with-selected', + run: async ({ page, expect }) => { + const items = page.locator('.p-tieredmenu-root-list > .p-tieredmenu-item'); + expect(await items.count(), 'пункты').toBe(3); + expect((await items.first().innerText()).trim(), 'первый пункт').toBe('Отправления'); + } + }, + ...STORIES.map(smoke), + { ...smoke(STORIES[0]), name: `Smoke: ${STORIES[0].name} (тёмная тема)`, theme: 'dark' } + ] +}; diff --git a/e2e/specs/timeline.e2e.mjs b/e2e/specs/timeline.e2e.mjs new file mode 100644 index 00000000..812caca3 --- /dev/null +++ b/e2e/specs/timeline.e2e.mjs @@ -0,0 +1,63 @@ +/** + * E2E-спека Timeline: события, маркеры, ориентация и opposite-контент. + */ + +const STORIES = [ + { id: 'components-data-timeline--custom-icon', name: 'Custom Icon' }, + { id: 'components-data-timeline--custom-marker', name: 'Custom Marker' }, + { id: 'components-data-timeline--dashed-line', name: 'Dashed Line' }, + { id: 'components-data-timeline--default', name: 'Default' }, + { id: 'components-data-timeline--horizontal', name: 'Horizontal' }, + { id: 'components-data-timeline--marker-color', name: 'Marker Color' }, + { id: 'components-data-timeline--opposite', name: 'Opposite' } +]; + +const smoke = (story) => ({ + name: `Smoke: ${story.name}`, + story: story.id, + run: async ({ page, expect, errors }) => { + expect(errors.filter((error) => error.type === 'pageerror').map((error) => error.text), 'ошибки страницы').toEqual([]); + expect(await page.locator('#storybook-root > *').count(), 'корень story').toBeGreaterThan(0); + const box = await page.locator('#storybook-root').boundingBox(); + expect(Boolean(box && box.width > 0), 'ширина story').toBe(true); + } +}); + +export default { + component: 'timeline', + stories: Object.fromEntries(STORIES.map((story) => [story.id, story.id])), + tests: [ + { + name: 'Default: четыре события и маркера', + story: 'components-data-timeline--default', + run: async ({ page, expect }) => { + expect(await page.locator('.p-timeline-event').count(), 'события').toBe(4); + expect(await page.locator('.p-timeline-event-marker').count(), 'маркеры').toBe(4); + expect(await page.locator('#storybook-root').innerText(), 'текст').toContain('Заказ создан'); + } + }, + { + name: 'Horizontal: горизонтальная ориентация', + story: 'components-data-timeline--horizontal', + run: async ({ page, expect }) => { + expect(await page.locator('.p-timeline').getAttribute('class'), 'класс').toContain('p-timeline-horizontal'); + } + }, + { + name: 'Opposite: контент с противоположной стороны', + story: 'components-data-timeline--opposite', + run: async ({ page, expect }) => { + expect(await page.locator('.p-timeline-event-opposite').count(), 'opposite-блоки').toBe(4); + } + }, + { + name: 'Dashed Line: коннекторы между событиями', + story: 'components-data-timeline--dashed-line', + run: async ({ page, expect }) => { + expect(await page.locator('.p-timeline-event-connector').count(), 'коннекторы').toBe(3); + } + }, + ...STORIES.map(smoke), + { ...smoke(STORIES[0]), name: `Smoke: ${STORIES[0].name} (тёмная тема)`, theme: 'dark' } + ] +}; diff --git a/e2e/specs/toast.e2e.mjs b/e2e/specs/toast.e2e.mjs new file mode 100644 index 00000000..dbb404d9 --- /dev/null +++ b/e2e/specs/toast.e2e.mjs @@ -0,0 +1,65 @@ +/** + * E2E-спека Toast: сообщения, добавление, severity и закрытие. + */ + +const STORIES = [ + { id: 'components-feedback-toast--default', name: 'Default' }, + { id: 'components-feedback-toast--position', name: 'Position' }, + { id: 'components-feedback-toast--slots', name: 'Slots' }, + { id: 'components-feedback-toast--width', name: 'Width' }, + { id: 'components-feedback-toast--with-close-button', name: 'WithCloseButton' } +]; + +const smoke = (story) => ({ + name: `Smoke: ${story.name}`, + story: story.id, + run: async ({ page, expect, errors }) => { + expect(errors.filter((error) => error.type === 'pageerror').map((error) => error.text), 'ошибки страницы').toEqual([]); + expect(await page.locator('#storybook-root > *').count(), 'корень story').toBeGreaterThan(0); + const box = await page.locator('#storybook-root').boundingBox(); + expect(Boolean(box && box.width > 0), 'ширина story').toBe(true); + } +}); + +export default { + component: 'toast', + stories: Object.fromEntries(STORIES.map((story) => [story.id, story.id])), + tests: [ + { + name: 'Default: четыре сообщения и добавление пятого', + story: 'components-feedback-toast--default', + run: async ({ page, expect, wait }) => { + expect(await page.locator('.p-toast-message').count(), 'сообщения').toBe(4); + await page.locator('button', { hasText: 'Показать: Успех' }).click(); + await wait(async () => (await page.locator('.p-toast-message').count()) === 5); + expect(await page.locator('.p-toast-message').count(), 'после клика').toBe(5); + } + }, + { + name: 'Default: сообщение имеет роль alert/status', + story: 'components-feedback-toast--default', + knownIssue: 'p-toast-message без role: скринридер не объявляет всплывающее сообщение', + run: async ({ page, expect }) => { + const roles = await page.locator('.p-toast-message').evaluateAll((messages) => + messages.map((message) => message.getAttribute('role')) + ); + expect(roles.every((role) => role === 'alert' || role === 'status'), 'роли сообщений').toBe(true); + } + }, + { + name: 'WithCloseButton: кнопка закрытия удаляет сообщение', + story: 'components-feedback-toast--with-close-button', + knownIssue: 'Клик по p-toast-close-button не удаляет сообщение: счётчик остаётся прежним', + run: async ({ page, expect, wait }) => { + const before = await page.locator('.p-toast-message').count(); + const close = page.locator('.p-toast-close-button').first(); + expect(await close.count(), 'кнопка закрытия').toBeGreaterThan(0); + await close.click(); + await wait(async () => (await page.locator('.p-toast-message').count()) === before - 1, { timeout: 2000 }); + expect(await page.locator('.p-toast-message').count(), 'после закрытия').toBe(before - 1); + } + }, + ...STORIES.map(smoke), + { ...smoke(STORIES[0]), name: `Smoke: ${STORIES[0].name} (тёмная тема)`, theme: 'dark' } + ] +}; diff --git a/e2e/specs/togglebutton.e2e.mjs b/e2e/specs/togglebutton.e2e.mjs new file mode 100644 index 00000000..cca41bd3 --- /dev/null +++ b/e2e/specs/togglebutton.e2e.mjs @@ -0,0 +1,82 @@ +/** + * E2E-спека ToggleButton: роль, переключение, состояния и размеры. + */ + +const STORIES = [ + { id: 'components-form-togglebutton--default', name: 'Default' }, + { id: 'components-form-togglebutton--disabled', name: 'Disabled' }, + { id: 'components-form-togglebutton--fluid', name: 'Fluid' }, + { id: 'components-form-togglebutton--icon-only', name: 'IconOnly' }, + { id: 'components-form-togglebutton--sizes', name: 'Sizes' }, + { id: 'components-form-togglebutton--with-icon', name: 'WithIcon' } +]; + +const smoke = (story) => ({ + name: `Smoke: ${story.name}`, + story: story.id, + run: async ({ page, expect, errors }) => { + expect(errors.filter((error) => error.type === 'pageerror').map((error) => error.text), 'ошибки страницы').toEqual([]); + expect(await page.locator('#storybook-root > *').count(), 'корень story').toBeGreaterThan(0); + const box = await page.locator('#storybook-root').boundingBox(); + expect(Boolean(box && box.width > 0), 'ширина story').toBe(true); + } +}); + +export default { + component: 'togglebutton', + stories: Object.fromEntries(STORIES.map((story) => [story.id, story.id])), + tests: [ + { + name: 'Default: role=button и переключение по клику', + story: 'components-form-togglebutton--default', + run: async ({ page, expect }) => { + const button = page.locator('.p-togglebutton').first(); + expect(await button.getAttribute('role'), 'role').toBe('button'); + expect(await button.getAttribute('aria-pressed'), 'до клика').toBe('false'); + + await button.click(); + expect(await button.getAttribute('aria-pressed'), 'после клика').toBe('true'); + } + }, + { + name: 'Keyboard: Space переключает', + story: 'components-form-togglebutton--default', + run: async ({ page, expect }) => { + const button = page.locator('.p-togglebutton').first(); + await button.focus(); + await page.keyboard.press('Space'); + expect(await button.getAttribute('aria-pressed'), 'после Space').toBe('true'); + } + }, + { + name: 'Disabled: aria-disabled и класс p-disabled', + story: 'components-form-togglebutton--disabled', + run: async ({ page, expect }) => { + const button = page.locator('.p-togglebutton').first(); + expect(await button.getAttribute('class'), 'класс').toContain('p-disabled'); + expect(await button.getAttribute('aria-disabled'), 'aria-disabled').toBe('true'); + } + }, + { + name: 'Sizes: 32 < 40 < 56 < 64', + story: 'components-form-togglebutton--sizes', + run: async ({ page, expect }) => { + const heights = await page.locator('.p-togglebutton').evaluateAll((buttons) => + buttons.map((button) => Math.round(button.getBoundingClientRect().height)) + ); + expect(heights.length, 'количество').toBe(4); + expect(heights[0] < heights[1] && heights[1] < heights[2] && heights[2] < heights[3], 'высоты возрастают').toBe(true); + } + }, + { + name: 'IconOnly: квадратная кнопка', + story: 'components-form-togglebutton--icon-only', + run: async ({ page, expect }) => { + const box = await page.locator('.p-togglebutton').first().boundingBox(); + expect(Math.round(box.width), 'ширина').toBe(Math.round(box.height)); + } + }, + ...STORIES.map(smoke), + { ...smoke(STORIES[0]), name: `Smoke: ${STORIES[0].name} (тёмная тема)`, theme: 'dark' } + ] +}; diff --git a/e2e/specs/toggleswitch.e2e.mjs b/e2e/specs/toggleswitch.e2e.mjs new file mode 100644 index 00000000..83b188f4 --- /dev/null +++ b/e2e/specs/toggleswitch.e2e.mjs @@ -0,0 +1,79 @@ +/** + * E2E-спека ToggleSwitch: роль switch, переключение, состояния и клавиатура. + */ + +const STORIES = [ + { id: 'components-form-toggleswitch--bare', name: 'Bare' }, + { id: 'components-form-toggleswitch--default', name: 'Default' }, + { id: 'components-form-toggleswitch--positions', name: 'Positions' }, + { id: 'components-form-toggleswitch--states', name: 'States' } +]; + +const smoke = (story) => ({ + name: `Smoke: ${story.name}`, + story: story.id, + run: async ({ page, expect, errors }) => { + expect(errors.filter((error) => error.type === 'pageerror').map((error) => error.text), 'ошибки страницы').toEqual([]); + expect(await page.locator('#storybook-root > *').count(), 'корень story').toBeGreaterThan(0); + const box = await page.locator('#storybook-root').boundingBox(); + expect(Boolean(box && box.width > 0), 'ширина story').toBe(true); + } +}); + +export default { + component: 'toggleswitch', + stories: Object.fromEntries(STORIES.map((story) => [story.id, story.id])), + tests: [ + { + name: 'Default: role=switch, клик и aria-checked', + story: 'components-form-toggleswitch--default', + run: async ({ page, expect }) => { + const input = page.locator('.p-toggleswitch-input'); + expect(await input.getAttribute('role'), 'role').toBe('switch'); + expect(await input.getAttribute('aria-checked'), 'до клика').toBe('false'); + + await page.locator('.p-toggleswitch').click(); + expect(await input.isChecked(), 'checked').toBe(true); + expect(await input.getAttribute('aria-checked'), 'aria-checked').toBe('true'); + } + }, + { + name: 'Keyboard: Space переключает', + story: 'components-form-toggleswitch--default', + run: async ({ page, expect }) => { + const input = page.locator('.p-toggleswitch-input'); + await input.focus(); + await page.keyboard.press('Space'); + expect(await input.isChecked(), 'после Space').toBe(true); + } + }, + { + name: 'States: checked, disabled и invalid', + story: 'components-form-toggleswitch--states', + run: async ({ page, expect }) => { + expect(await page.locator('.p-toggleswitch-input').nth(1).isChecked(), 'второй включён').toBe(true); + expect(await page.locator('.p-toggleswitch-input').nth(2).isDisabled(), 'третий disabled').toBe(true); + expect(await page.locator('.p-toggleswitch').nth(3).getAttribute('class'), 'четвёртый invalid').toContain('p-invalid'); + } + }, + { + name: 'Positions: оба положения включены', + story: 'components-form-toggleswitch--positions', + run: async ({ page, expect }) => { + const checked = await page.locator('.p-toggleswitch-input').evaluateAll((elements) => elements.map((element) => element.checked)); + expect(checked, 'все включены').toEqual([true, true]); + } + }, + { + name: 'ToggleSwitch: tabindex не должен быть NaN', + story: 'components-form-toggleswitch--default', + knownIssue: 'PrimeNG выставляет tabindex="NaN" на нативный input', + run: async ({ page, expect }) => { + const tabindex = await page.locator('.p-toggleswitch-input').getAttribute('tabindex'); + expect(tabindex === null || /^-?\d+$/.test(tabindex), 'валидный tabindex').toBe(true); + } + }, + ...STORIES.map(smoke), + { ...smoke(STORIES[0]), name: `Smoke: ${STORIES[0].name} (тёмная тема)`, theme: 'dark' } + ] +}; diff --git a/e2e/specs/tooltip.e2e.mjs b/e2e/specs/tooltip.e2e.mjs new file mode 100644 index 00000000..73dab31a --- /dev/null +++ b/e2e/specs/tooltip.e2e.mjs @@ -0,0 +1,66 @@ +/** + * E2E-спека Tooltip: показ, скрытие, позиции и связь с триггером. + */ + +const STORIES = [ + { id: 'components-overlay-tooltip--default', name: 'Default' }, + { id: 'components-overlay-tooltip--delay', name: 'Delay' }, + { id: 'components-overlay-tooltip--event-focus', name: 'Event' }, + { id: 'components-overlay-tooltip--positions', name: 'Positions' } +]; + +const smoke = (story) => ({ + name: `Smoke: ${story.name}`, + story: story.id, + run: async ({ page, expect, errors }) => { + expect(errors.filter((error) => error.type === 'pageerror').map((error) => error.text), 'ошибки страницы').toEqual([]); + expect(await page.locator('#storybook-root > *').count(), 'корень story').toBeGreaterThan(0); + const box = await page.locator('#storybook-root').boundingBox(); + expect(Boolean(box && box.width > 0), 'ширина story').toBe(true); + } +}); + +export default { + component: 'tooltip', + stories: Object.fromEntries(STORIES.map((story) => [story.id, story.id])), + tests: [ + { + name: 'Default: подсказка появляется при наведении и исчезает', + story: 'components-overlay-tooltip--default', + run: async ({ page, expect }) => { + const trigger = page.locator('button', { hasText: 'Наведи на меня' }); + await trigger.hover(); + await page.waitForSelector('.p-tooltip', { state: 'visible' }); + expect(await page.locator('.p-tooltip').innerText(), 'текст').toBe('Это текст подсказки'); + + await page.mouse.move(1000, 700); + await page.waitForTimeout(500); + expect(await page.locator('.p-tooltip').isVisible().catch(() => false), 'после ухода').toBe(false); + } + }, + { + name: 'Default: роль tooltip', + story: 'components-overlay-tooltip--default', + run: async ({ page, expect }) => { + await page.locator('button', { hasText: 'Наведи на меня' }).hover(); + await page.waitForSelector('.p-tooltip', { state: 'visible' }); + expect(await page.locator('.p-tooltip').getAttribute('role'), 'role').toBe('tooltip'); + } + }, + { + name: 'Default: триггер связан с подсказкой через aria-describedby', + story: 'components-overlay-tooltip--default', + knownIssue: 'У триггера нет aria-describedby, у tooltip нет id: подсказка не связывается с элементом', + run: async ({ page, expect }) => { + const trigger = page.locator('button', { hasText: 'Наведи на меня' }); + await trigger.hover(); + await page.waitForSelector('.p-tooltip', { state: 'visible' }); + const describedBy = await trigger.getAttribute('aria-describedby'); + const tooltipId = await page.locator('.p-tooltip').getAttribute('id'); + expect(Boolean(describedBy && tooltipId && describedBy === tooltipId), 'связь').toBe(true); + } + }, + ...STORIES.map(smoke), + { ...smoke(STORIES[0]), name: `Smoke: ${STORIES[0].name} (тёмная тема)`, theme: 'dark' } + ] +}; diff --git a/e2e/storybook-runner.mjs b/e2e/storybook-runner.mjs new file mode 100644 index 00000000..d54241bf --- /dev/null +++ b/e2e/storybook-runner.mjs @@ -0,0 +1,153 @@ +#!/usr/bin/env node +/** + * Запуск встроенного @storybook/test-runner только по одному компоненту. + * + * CLI раннера не фильтрует stories по title: он берёт весь index.json Storybook. + * Поэтому поднимаем локальный прокси, который отдаёт отфильтрованный index.json, + * а всё остальное (iframe.html, бандлы, картинки) проксирует в живой Storybook. + * + * Запуск: + * node e2e/storybook-runner.mjs button + * node e2e/storybook-runner.mjs Components/Form/Select --url=http://localhost:6007 + * node e2e/storybook-runner.mjs select -- --maxWorkers=2 --verbose + * + * Всё после `--` уходит в test-storybook без изменений. + */ +import http from 'node:http'; +import https from 'node:https'; +import { spawn } from 'node:child_process'; +import { existsSync } from 'node:fs'; +import { dirname, join, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { log } from './lib/log.mjs'; + +const __dirname = dirname(fileURLToPath(import.meta.url)); +const ROOT = resolve(__dirname, '..'); +const RUNNER_BIN = join(ROOT, 'node_modules/@storybook/test-runner/dist/test-storybook.js'); + +const argv = process.argv.slice(2); +const separator = argv.indexOf('--'); +const ownArgs = separator === -1 ? argv : argv.slice(0, separator); +const runnerArgs = separator === -1 ? [] : argv.slice(separator + 1); + +const target = ownArgs.find((arg) => !arg.startsWith('-')); +const flag = (name, fallback) => { + const prefix = `--${name}=`; + const found = ownArgs.find((arg) => arg.startsWith(prefix)); + return found ? found.slice(prefix.length) : fallback; +}; + +if (!target) { + console.error('Укажите компонент или title: node e2e/storybook-runner.mjs '); + process.exit(2); +} +if (!existsSync(RUNNER_BIN)) { + console.error(`Не найден встроенный раннер: ${RUNNER_BIN}. Установите @storybook/test-runner.`); + process.exit(2); +} + +const baseUrl = flag('url', process.env.E2E_STORYBOOK_URL || 'http://localhost:6007').replace(/\/+$/, ''); +const includeDocs = ownArgs.includes('--include-docs'); + +const normalize = (value) => value.toLowerCase().replace(/[^a-z0-9]/g, ''); + +const matches = (entry) => { + if (!includeDocs && entry.type === 'docs') return false; + const title = (entry.title ?? '').toLowerCase(); + const needle = target.toLowerCase(); + if (needle.includes('/')) return title.includes(needle); + + // Компонент в коде — `date-picker`, title — `DatePicker`, id — `...datepicker--`. + const normalizedTitle = normalize(title); + const normalizedNeedle = normalize(needle); + return normalizedTitle.endsWith(normalizedNeedle) || normalize(entry.id).startsWith(`${normalizedNeedle}--`); +}; + +const fetchIndex = async () => { + const response = await fetch(`${baseUrl}/index.json`); + if (!response.ok) throw new Error(`Storybook ${baseUrl} ответил ${response.status} на /index.json`); + return response.json(); +}; + +let filtered; +let indexVersion = 5; +try { + const index = await fetchIndex(); + if (typeof index.v === 'number') indexVersion = index.v; + const entries = index.entries ?? {}; + filtered = Object.fromEntries(Object.entries(entries).filter(([, entry]) => matches(entry))); + + if (Object.keys(filtered).length === 0) { + console.error(`В Storybook ${baseUrl} нет stories под «${target}».`); + console.error('Проверьте title: curl -s http://localhost:6007/index.json | node -e "..."'); + process.exit(3); + } +} catch (error) { + console.error(error.message); + console.error('Storybook должен быть запущен: npm run storybook -- --port 6007'); + process.exit(2); +} + +const filteredIds = Object.keys(filtered); +log(`\nВстроенный test-runner · ${target} · ${filteredIds.length} stories:`); +for (const id of filteredIds.slice(0, 8)) log(` · ${id}`); +if (filteredIds.length > 8) log(` · … ещё ${filteredIds.length - 8}`); + +const targetUrl = new URL(baseUrl); +const transport = targetUrl.protocol === 'https:' ? https : http; +const targetPort = Number(targetUrl.port) || (targetUrl.protocol === 'https:' ? 443 : 80); + +const server = http.createServer((req, res) => { + if (req.url === '/index.json' || req.url?.startsWith('/index.json?')) { + const body = JSON.stringify({ v: indexVersion, entries: filtered }); + res.writeHead(200, { 'content-type': 'application/json', 'cache-control': 'no-store' }); + res.end(body); + return; + } + + const upstream = transport.request( + { + hostname: targetUrl.hostname, + port: targetPort, + path: req.url, + method: req.method, + headers: { ...req.headers, host: targetUrl.host } + }, + (upstreamResponse) => { + res.writeHead(upstreamResponse.statusCode ?? 502, upstreamResponse.headers); + upstreamResponse.pipe(res); + } + ); + + upstream.on('error', (error) => { + res.writeHead(502, { 'content-type': 'text/plain' }); + res.end(`Proxy error: ${error.message}`); + }); + + req.pipe(upstream); +}); + +// WebSocket HMR в тестах не нужен: рендер story идёт по HTTP. +server.on('upgrade', (req, socket) => socket.destroy()); + +await new Promise((resolveListen) => server.listen(0, '127.0.0.1', resolveListen)); +const proxyUrl = `http://127.0.0.1:${server.address().port}`; +log(`Прокси: ${proxyUrl} → ${baseUrl}`); + +const runner = spawn(process.execPath, [RUNNER_BIN, '--index-json', '--url', proxyUrl, ...runnerArgs], { + cwd: ROOT, + stdio: 'inherit', + env: process.env +}); + +runner.on('exit', (code) => { + server.close(); + process.exit(code ?? 1); +}); + +for (const signal of ['SIGINT', 'SIGTERM']) { + process.on(signal, () => { + runner.kill(signal); + server.close(); + }); +} diff --git a/package-lock.json b/package-lock.json index 8ca02dcc..a1010571 100644 --- a/package-lock.json +++ b/package-lock.json @@ -42,6 +42,7 @@ "@tailwindcss/postcss": "4.3.1", "@types/jasmine": "5.1.13", "@typescript-eslint/eslint-plugin": "7.18.0", + "axe-playwright": "2.2.2", "eslint": "8.57.1", "eslint-config-prettier": "9.1.2", "eslint-plugin-import": "2.32.0", @@ -49,6 +50,7 @@ "eslint-plugin-prefer-arrow": "1.2.3", "eslint-plugin-storybook": "10.1.8", "jasmine-core": "5.13.0", + "jest-image-snapshot": "6.5.2", "js-yaml": "^4.1.0", "karma": "6.4.4", "karma-chrome-launcher": "3.2.0", @@ -56,6 +58,7 @@ "karma-jasmine": "5.1.0", "karma-jasmine-html-reporter": "2.1.0", "ng-packagr": "20.3.2", + "playwright": "1.62.1", "prettier": "3.7.4", "primeng": "20.4.0", "rxjs": "7.8.2", @@ -9069,6 +9072,13 @@ "dev": true, "license": "MIT" }, + "node_modules/@types/junit-report-builder": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/@types/junit-report-builder/-/junit-report-builder-3.0.2.tgz", + "integrity": "sha512-R5M+SYhMbwBeQcNXYWNCZkl09vkVfAtcPIaCGdzIkkbeaTrVbGQ7HVgi4s+EmM/M1K4ZuWQH0jGcvMvNePfxYA==", + "dev": true, + "license": "MIT" + }, "node_modules/@types/mdx": { "version": "2.0.13", "resolved": "https://registry.npmjs.org/@types/mdx/-/mdx-2.0.13.tgz", @@ -10966,6 +10976,39 @@ "node": ">=4" } }, + "node_modules/axe-html-reporter": { + "version": "2.2.11", + "resolved": "https://registry.npmjs.org/axe-html-reporter/-/axe-html-reporter-2.2.11.tgz", + "integrity": "sha512-WlF+xlNVgNVWiM6IdVrsh+N0Cw7qupe5HT9N6Uyi+aN7f6SSi92RDomiP1noW8OWIV85V6x404m5oKMeqRV3tQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "mustache": "^4.0.1" + }, + "engines": { + "node": ">=8.9.0" + }, + "peerDependencies": { + "axe-core": ">=3" + } + }, + "node_modules/axe-playwright": { + "version": "2.2.2", + "resolved": "https://registry.npmjs.org/axe-playwright/-/axe-playwright-2.2.2.tgz", + "integrity": "sha512-h350/grzDCPgpuWV7eEOqr/f61Xn07Gi9f9B3Ew4rW6/nFtpdEJYW6jgRATorgAGXjEAYFTnaY3sEys39wDw4A==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/junit-report-builder": "^3.0.2", + "axe-core": "^4.10.1", + "axe-html-reporter": "2.2.11", + "junit-report-builder": "^5.1.1", + "picocolors": "^1.1.1" + }, + "peerDependencies": { + "playwright": ">1.0.0" + } + }, "node_modules/axios": { "version": "1.20.0", "resolved": "https://registry.npmjs.org/axios/-/axios-1.20.0.tgz", @@ -16589,6 +16632,16 @@ "node": ">= 0.4" } }, + "node_modules/get-stdin": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/get-stdin/-/get-stdin-5.0.1.tgz", + "integrity": "sha512-jZV7n6jGE3Gt7fgSTJoz91Ak5MuTLwMwkoYdjxuJ/AmjIsE1UC03y/IWkZCQGEvVNS9qoRNwy5BCqxImv0FVeA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.12.0" + } + }, "node_modules/get-stream": { "version": "5.2.0", "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-5.2.0.tgz", @@ -16897,6 +16950,13 @@ "node": ">= 4" } }, + "node_modules/glur": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/glur/-/glur-1.1.2.tgz", + "integrity": "sha512-l+8esYHTKOx2G/Aao4lEQ0bnHWg4fWtJbVoZZT9Knxi01pB8C80BR85nONLFwkkQoFRCmXY+BUcGZN3yZ2QsRA==", + "dev": true, + "license": "MIT" + }, "node_modules/gopd": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", @@ -19347,6 +19407,33 @@ "url": "https://github.com/chalk/supports-color?sponsor=1" } }, + "node_modules/jest-image-snapshot": { + "version": "6.5.2", + "resolved": "https://registry.npmjs.org/jest-image-snapshot/-/jest-image-snapshot-6.5.2.tgz", + "integrity": "sha512-frenWThr5ddnnokcX5N4gwi41hA5TiUOdhv/JoGcJrOaktHjrk4/7XbiHKW52lgKX+vei6QkRlgM7fkYQ15nPg==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "chalk": "^4.0.0", + "get-stdin": "^5.0.1", + "glur": "^1.1.2", + "lodash": "^4.17.4", + "pixelmatch": "^5.1.0", + "pngjs": "^3.4.0", + "ssim.js": "^3.1.1" + }, + "engines": { + "node": "^14.15.0 || ^16.10.0 || >=18.0.0" + }, + "peerDependencies": { + "jest": ">=20 <31" + }, + "peerDependenciesMeta": { + "jest": { + "optional": true + } + } + }, "node_modules/jest-junit": { "version": "16.0.0", "resolved": "https://registry.npmjs.org/jest-junit/-/jest-junit-16.0.0.tgz", @@ -20305,6 +20392,47 @@ ], "license": "MIT" }, + "node_modules/junit-report-builder": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/junit-report-builder/-/junit-report-builder-5.1.2.tgz", + "integrity": "sha512-HzvLbEQcoqN2LmGnloShxu2hLadi/rkOTU3zt61UeMICLS0wGDvbf8neIi6+bGkxMnAePIcFMFnbqV+r6YvwxA==", + "dev": true, + "license": "MIT", + "dependencies": { + "lodash": "^4.18.1", + "make-dir": "^3.1.0", + "xmlbuilder": "^15.1.1" + }, + "engines": { + "node": ">=16" + } + }, + "node_modules/junit-report-builder/node_modules/make-dir": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-3.1.0.tgz", + "integrity": "sha512-g3FeP20LNwhALb/6Cz6Dd4F2ngze0jz7tbzrD2wAV+o9FeNHe4rL+yK2md0J/fiSf1sa1ADhXqi5+oVwOM/eGw==", + "dev": true, + "license": "MIT", + "dependencies": { + "semver": "^6.0.0" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/junit-report-builder/node_modules/semver": { + "version": "6.3.2", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.2.tgz", + "integrity": "sha512-GYrCADwpu6yV5OAvchkQ27Z5wwMxWAEMg5NNWjyHh/5DboFFqbdbvYNIvZouQpxXyeMPoTOh0vdPYKlf0ZswdQ==", + "dev": true, + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + } + }, "node_modules/karma": { "version": "6.4.4", "resolved": "https://registry.npmjs.org/karma/-/karma-6.4.4.tgz", @@ -21463,9 +21591,9 @@ } }, "node_modules/lodash": { - "version": "4.17.21", - "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz", - "integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==", + "version": "4.18.1", + "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.18.1.tgz", + "integrity": "sha512-dMInicTPVE8d1e5otfwmmjlxkZoUpiVLwyeTdUsi/Caj/gfzzblBcCE5sRHV/AsjuCmxWrte2TNGSYuCeCq+0Q==", "dev": true, "license": "MIT" }, @@ -22426,6 +22554,16 @@ "multicast-dns": "cli.js" } }, + "node_modules/mustache": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/mustache/-/mustache-4.2.0.tgz", + "integrity": "sha512-71ippSywq5Yb7/tVYyGbkBggbU8H3u5Rz56fH60jGFgr8uHwxs+aSKeqmluIVzM0m0kB7xQjKS6qPfd0b2ZoqQ==", + "dev": true, + "license": "MIT", + "bin": { + "mustache": "bin/mustache" + } + }, "node_modules/mute-stream": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/mute-stream/-/mute-stream-2.0.0.tgz", @@ -24442,6 +24580,29 @@ "@napi-rs/nice": "^1.0.4" } }, + "node_modules/pixelmatch": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/pixelmatch/-/pixelmatch-5.3.0.tgz", + "integrity": "sha512-o8mkY4E/+LNUf6LzX96ht6k6CEDi65k9G2rjMtBe9Oo+VPKSvl+0GKHuH/AlG+GA5LPG/i5hrekkxUc3s2HU+Q==", + "dev": true, + "license": "ISC", + "dependencies": { + "pngjs": "^6.0.0" + }, + "bin": { + "pixelmatch": "bin/pixelmatch" + } + }, + "node_modules/pixelmatch/node_modules/pngjs": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/pngjs/-/pngjs-6.0.0.tgz", + "integrity": "sha512-TRzzuFRRmEoSW/p1KVAmiOgPco2Irlah+bGFCeNfJXxxYGwSw7YwAOAcd7X28K/m5bjBWKsC29KyoMfHbypayg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12.13.0" + } + }, "node_modules/pkce-challenge": { "version": "5.0.1", "resolved": "https://registry.npmjs.org/pkce-challenge/-/pkce-challenge-5.0.1.tgz", @@ -24515,6 +24676,16 @@ "node": "^8.16.0 || ^10.6.0 || >=11.0.0" } }, + "node_modules/pngjs": { + "version": "3.4.0", + "resolved": "https://registry.npmjs.org/pngjs/-/pngjs-3.4.0.tgz", + "integrity": "sha512-NCrCHhWmnQklfH4MtJMRjZ2a8c80qXeMlQMv2uVp9ISJMTt562SbGd6n2oq0PaPgKm7Z6pL9E2UlLIhC+SHL3w==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=4.0.0" + } + }, "node_modules/polka": { "version": "0.5.2", "resolved": "https://registry.npmjs.org/polka/-/polka-0.5.2.tgz", @@ -27327,6 +27498,13 @@ "dev": true, "license": "BSD-3-Clause" }, + "node_modules/ssim.js": { + "version": "3.5.0", + "resolved": "https://registry.npmjs.org/ssim.js/-/ssim.js-3.5.0.tgz", + "integrity": "sha512-Aj6Jl2z6oDmgYFFbQqK7fght19bXdOxY7Tj03nF+03M9gCBAjeIiO8/PlEGMfKDwYpw4q6iBqVq2YuREorGg/g==", + "dev": true, + "license": "MIT" + }, "node_modules/ssri": { "version": "12.0.0", "resolved": "https://registry.npmjs.org/ssri/-/ssri-12.0.0.tgz", @@ -30662,6 +30840,16 @@ "dev": true, "license": "MIT" }, + "node_modules/xmlbuilder": { + "version": "15.1.1", + "resolved": "https://registry.npmjs.org/xmlbuilder/-/xmlbuilder-15.1.1.tgz", + "integrity": "sha512-yMqGBqtXyeN1e3TGYvgNgDVZ3j84W4cwkOXQswghol6APgZWaff9lnbvN7MHYJOiXsvGPXtjTYJEiC9J2wv9Eg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8.0" + } + }, "node_modules/y18n": { "version": "5.0.8", "resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz", diff --git a/package.json b/package.json index db93761c..2b2226dd 100644 --- a/package.json +++ b/package.json @@ -26,7 +26,10 @@ "generate:tailwind": "node tailwind/generate.mjs", "security:check": "npm audit --production --audit-level high", "copy:dist": "cpx 'src/lib/providers/prime-preset/**/*.{json,ts}' dist/ && cpx 'src-tokens/theme.preset.ts' dist/", - "validate:figma-cc": "node scripts/figma-code-connect/validate.mjs" + "validate:figma-cc": "node scripts/figma-code-connect/validate.mjs", + "test:component": "node e2e/check.mjs", + "test:e2e": "node e2e/all.mjs", + "test:e2e:builtin": "node e2e/builtin-all.mjs" }, "repository": "github:cdek-it/angular-ui-kit", "devDependencies": { @@ -59,6 +62,7 @@ "@tailwindcss/postcss": "4.3.1", "@types/jasmine": "5.1.13", "@typescript-eslint/eslint-plugin": "7.18.0", + "axe-playwright": "2.2.2", "eslint": "8.57.1", "eslint-config-prettier": "9.1.2", "eslint-plugin-import": "2.32.0", @@ -66,6 +70,7 @@ "eslint-plugin-prefer-arrow": "1.2.3", "eslint-plugin-storybook": "10.1.8", "jasmine-core": "5.13.0", + "jest-image-snapshot": "6.5.2", "js-yaml": "^4.1.0", "karma": "6.4.4", "karma-chrome-launcher": "3.2.0", @@ -73,6 +78,7 @@ "karma-jasmine": "5.1.0", "karma-jasmine-html-reporter": "2.1.0", "ng-packagr": "20.3.2", + "playwright": "1.62.1", "prettier": "3.7.4", "primeng": "20.4.0", "rxjs": "7.8.2", diff --git a/src/stories/GettingStarted.mdx b/src/stories/GettingStarted.mdx index 6a756763..595c4767 100644 --- a/src/stories/GettingStarted.mdx +++ b/src/stories/GettingStarted.mdx @@ -54,7 +54,19 @@ export class DemoComponent {} Список компонентов и их API — в разделе **Components** слева. -## 4. Tailwind v4 (опционально) +## 4. Проверить компонент + +Перед PR компонент проверяется одной командой: встроенный Storybook test-runner и e2e-сценарии. + +```bash +node e2e/check.mjs +``` + +Команда сама поднимет Storybook, прогонит оба уровня и запишет отчёт в `e2e/reports/-check.json`. + +Подробнее — страница «Тестирование» в разделе «Начало работы». + +## 5. Tailwind v4 (опционально) Кит отдаёт готовую Tailwind v4 тему (`@theme`), сгенерированную из тех же дизайн-токенов. Чтобы получить утилиты кита (цвета, типографику, radius, тени, spacing), добавьте в `styles.scss`: @@ -64,7 +76,7 @@ export class DemoComponent {} @use "@cdek-it/angular-ui-kit/tailwind"; ``` -## 5. Иконки (опционально) +## 6. Иконки (опционально) Компоненты используют [Tabler Icons](https://tabler.io/icons). Чтобы работали классы `ti ti-*`, установите пакет и подключите шрифт: diff --git a/src/stories/Testing.mdx b/src/stories/Testing.mdx new file mode 100644 index 00000000..51079a22 --- /dev/null +++ b/src/stories/Testing.mdx @@ -0,0 +1,132 @@ +import { Meta } from '@storybook/addon-docs/blocks'; + + + +# Тестирование компонентов + +Как проверить компонент перед PR: одной командой. + +## Коротко + +```bash +node e2e/check.mjs +``` + +Команда сама поднимет Storybook (если он не запущен), прогонит встроенный Storybook test-runner и e2e-спеку компонента и запишет общий отчёт: + +- **куда** — `e2e/reports/-check.json`; +- **формат** — JSON со статусами `builtin` и `e2e`, exit-кодами и путями к детальным отчётам; +- **что возвращает** — код завершения процесса: `0` — всё прошло, `1` — есть упавшие тесты, `2` — ошибка запуска (например, Storybook не поднялся или компонент не найден). + +Код `0/1` нужен не для чтения глазами, а для автоматики: терминал и IDE подсвечивают результат, CI останавливает пайплайн на `1` и не пропускает PR. Тестировщик при этом видит итог в терминале, а детали и скриншоты — в JSON-отчёте и `e2e/artifacts/`. + +## Два уровня проверок + +**Встроенный test-runner** + +- **Роль** — регрессионная сеть по всему каталогу stories компонента. +- **Польза** — без написания тестов ловит упавший рендер, новые critical/serious a11y-нарушения и дрейф стилей после правок токенов. +- **Что проверяет** — рендер каждой story, `play`, axe и вычисленные стили. +- **Когда падает** — новая a11y-ошибка или расхождение с baseline. +- **Отчёт** — вывод Jest и baseline. + +**E2E-раннер** + +- **Роль** — проверка пользовательских сценариев компонента. +- **Польза** — ловит поломки клавиатуры, фокуса, оверлеев и состояний, которые не видны в статичной story. +- **Что проверяет** — клики, ввод, клавиатуру, фокус, открытие/закрытие и выбранные значения. +- **Когда падает** — сломанный сценарий или неверное состояние. +- **Отчёт** — `e2e/reports/*.json` и скриншоты. + +## Быстрый старт + +```bash +# Storybook нужен один раз; check.mjs поднимет его сам +npm run storybook -- --port 6007 + +# всё по одному компоненту +node e2e/check.mjs +node e2e/check.mjs --theme=light,dark + +# только один уровень +node e2e/check.mjs --no-e2e +node e2e/check.mjs --no-builtin + +# все компоненты +node e2e/builtin-all.mjs +node e2e/all.mjs +``` + +Storybook проекта — `http://localhost:6007`; этот адрес `check.mjs` использует по умолчанию. Если Storybook запущен на другом порту, передайте свой `--url`. + +## Что получилось + +- `e2e/reports/-check.json` — общий статус: `builtin`, `e2e`, exit-коды и пути к деталям; +- `e2e/reports/-builtin-runner.json` — результаты встроенного раннера; +- `e2e/reports/-e2e.json` — результаты e2e; +- `e2e/artifacts//` — скриншоты упавших тестов. + +`knownIssue` — известный дефект: тест остаётся в отчёте, но не валит прогон. `failed` — блокирует PR. + +## Добавить e2e новому компоненту + +Спека лежит в `e2e/specs/.e2e.mjs`: + +```js +export default { + component: '', + stories: { + default: 'components----default' + }, + tests: [ + { + name: 'Default: компонент отрендерен', + story: 'default', + run: async ({ page, expect }) => { + await page.waitForSelector(''); + expect(await page.locator('').count(), 'компонент').toBe(1); + } + } + ] +}; +``` + +Правила: + +- story id берите из живого `index.json`, а не из `storybook-static` — он отстаёт; +- селекторы — роли, `aria-*`, `data-pc-section`, а не сгенерированные `pn_id_*`; +- оверлеи PrimeNG живут в `body`, вне `#storybook-root`; +- один тест — один сценарий; общие шаги выносите в локальные хелперы; +- найденный дефект фиксируйте через `knownIssue`, а не удаляйте проверку. + +## Baseline + +Встроенный раннер сравнивает вычисленные стили и axe с baseline: + +- рабочая матрица использует `e2e/baselines`, её не нужно трогать вручную; +- для локального «чистого» прогона: `node e2e/check.mjs --fresh-baselines`; +- обновление baseline — осознанное действие: `UPDATE_STYLE_BASELINES=1` / `UPDATE_A11Y_BASELINE=1`. + +## CI + +```bash +node e2e/builtin-all.mjs +node e2e/all.mjs --theme=light +``` + +Оба шага должны быть зелёными; `e2e/reports` и `e2e/artifacts` складывайте в артефакты CI. + +## Частые ошибки + +- **Storybook не запущен** — уберите `--no-start-storybook` или поднимите Storybook вручную. +- **Компонент не найден** — укажите title: `node e2e/check.mjs /`. +- **Короткое имя неоднозначно** — используйте точный title `Components/`. +- **Story id не найден** — story переименовали, обновите id из `index.json`. +- **E2E-спека не подходит к ветке** — укажите другую через `--spec=`. + +## Чек-лист перед PR + +- `node e2e/check.mjs ` — exit `0`; +- `check-stories-source` и `check-stories-descriptions` — PASS; +- сборка библиотеки проходит; +- новые `knownIssue` описаны в отчёте и понятны ревьюеру.