Тестирование доступности с 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 рабочих дня.







