Тестування доступності з Lighthouse
Lighthouse — інструмент Google для аудиту якості веб-додатків: продуктивність, доступність, SEO, best practices. Оцінка доступності (0–100) базується на axe-core та охоплює WCAG 2.1 AA. Запускається через CLI, Chrome DevTools або Node.js API.
Lighthouse CLI
npm install -g lighthouse
# Базовий аудит
lighthouse https://example.com --only-categories=accessibility --output=json --output-path=report.json
# Аудит без браузера (Headless)
lighthouse https://example.com \
--chrome-flags="--headless --no-sandbox" \
--only-categories=accessibility \
--output=html,json \
--output-path=./reports/lighthouse
Node.js API для групового аудиту
// scripts/lighthouse-audit.js
const lighthouse = require('lighthouse');
const chromeLauncher = require('chrome-launcher');
const fs = require('fs');
const PAGES = [
{ url: 'http://localhost:3000', name: 'Головна' },
{ url: 'http://localhost:3000/catalog', name: 'Каталог' },
{ url: 'http://localhost:3000/product/1', name: 'Карточка товару' },
{ url: 'http://localhost:3000/checkout', name: 'Оформлення замовлення' },
];
async function runAudit() {
const chrome = await chromeLauncher.launch({
chromeFlags: ['--headless', '--no-sandbox', '--disable-gpu'],
});
const results = [];
try {
for (const page of PAGES) {
const runnerResult = await lighthouse(page.url, {
port: chrome.port,
onlyCategories: ['accessibility'],
formFactor: 'desktop',
throttling: { cpuSlowdownMultiplier: 1 },
screenEmulation: { disabled: true },
});
const score = runnerResult.lhr.categories.accessibility.score * 100;
const audits = runnerResult.lhr.audits;
// Збираємо тільки невдалі перевірки
const failures = Object.values(audits)
.filter(a => a.score !== null && a.score < 1 && a.score >= 0)
.map(a => ({ id: a.id, title: a.title, score: a.score }));
results.push({ ...page, score, failures });
console.log(`${page.name}: ${score}/100`);
}
} finally {
await chrome.kill();
}
// Генеруємо підсумок
const minScore = Math.min(...results.map(r => r.score));
console.log(`\nМінімальний результат: ${minScore}/100`);
fs.writeFileSync('lighthouse-summary.json', JSON.stringify(results, null, 2));
// Вихід якщо результат нижче порога
if (minScore < 90) {
console.error('Доступність нижче порога 90!');
process.exit(1);
}
}
runAudit().catch(console.error);
Ключові перевірки доступності в Lighthouse
| Audit ID | Опис | Вплив на оцінку |
|---|---|---|
color-contrast |
Контраст тексту (4.5:1 для AA) | Високий |
image-alt |
Alt атрибут у зображень | Високий |
button-name |
Кнопки з доступним іменем | Високий |
label |
Поля форми пов'язані з label | Високий |
heading-order |
Правильна ієрархія заголовків | Середній |
link-name |
Посилання з осмисленим текстом | Середній |
html-has-lang |
Lang атрибут у html елемента | Низький |
aria-* |
Коректність ARIA-атрибутів | Залежить |
Інтеграція з GitHub Actions
# .github/workflows/lighthouse.yml
name: Lighthouse Accessibility
on: [pull_request]
jobs:
lighthouse:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Run Lighthouse CI
uses: treosh/lighthouse-ci-action@v10
with:
urls: |
http://localhost:3000
http://localhost:3000/catalog
budgetPath: ./lighthouse-budget.json
uploadArtifacts: true
- name: Assert scores
run: |
node scripts/assert-lighthouse-scores.js
// lighthouse-budget.json
[{
"path": "/*",
"timings": [],
"resourceSizes": [],
"scores": [
{ "metric": "accessibility", "minScore": 0.9 }
]
}]
Терміни
Настройка Lighthouse-аудиту з бюджетами та CI-інтеграцією: 1–2 робочих дні.







