Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 62 additions & 0 deletions .github/workflows/component-tests.yml
Original file line number Diff line number Diff line change
@@ -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
9 changes: 9 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -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/
415 changes: 415 additions & 0 deletions .storybook/test-runner.ts

Large diffs are not rendered by default.

28 changes: 28 additions & 0 deletions e2e/README.md
Original file line number Diff line number Diff line change
@@ -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/<component>.e2e.mjs`.
- Отчёты: `e2e/reports/`, скриншоты падений: `e2e/artifacts/`.
- Baseline создаётся первым прогоном; обновление — `UPDATE_STYLE_BASELINES=1`.
- В `main` 52 спеки: `image` добавляется после мержа PR #200.
- CI: `.github/workflows/component-tests.yml`.
44 changes: 44 additions & 0 deletions e2e/all.mjs
Original file line number Diff line number Diff line change
@@ -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);
97 changes: 97 additions & 0 deletions e2e/build-registry.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
#!/usr/bin/env node
/**
* Реестр компонентов для e2e-работ: stories, группа, ветка.
*
* Источник stories — живой index.json Storybook (не storybook-static: он отстаёт).
* Ветка выбирается по конвенции `feature/<group>-<component>-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 ?? '—'}`);
}
99 changes: 99 additions & 0 deletions e2e/build-status.mjs
Original file line number Diff line number Diff line change
@@ -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}`);
Loading
Loading