Accessibility Testing with Selenium WebDriver & Axe Core
This skill enables automated accessibility analysis within the Selenium WebDriver framework using the axe-core engine to detect WCAG violations and best practice issues directly in the browser.
Activation: This skill is triggered when you need to validate WCAG compliance, scan for accessibility violations, test keyboard navigation, audit ARIA semantics, or generate a11y reports.
First Questions to Ask
- What app URL(s) or user flows are in scope (and what is explicitly out of scope)?
- Is there an existing Selenium setup and how is CI run?
- Which standard is the target (WCAG 2.1 AA by default), and are there org-specific policies?
- Which pages/components are highest risk (auth, checkout, forms, modals, navigation)?
- Are there known constraints (legacy markup, third-party widgets) that require exceptions?
Prerequisites
| Component |
Version |
Purpose |
| Java JDK |
21+ |
Runtime with modern features |
| Maven |
3.9+ |
Dependency management |
| Selenium WebDriver |
4.x |
Browser automation |
| axe-core-selenium |
4.10+ |
Deque axe-core integration |
| JUnit 5 |
5.10+ |
Test framework |
| AssertJ |
3.x |
Fluent assertions for readable failures |
| Allure |
2.x |
Reporting with a11y violation attachments |
Note: Use com.deque.html.axe-core:selenium Maven dependency for axe integration.
WCAG Compliance Levels
| Level |
Requirement |
Legal Status |
Axe Tags |
| Level A |
Basic accessibility (must have) |
Minimum legal requirement |
wcag2a, wcag21a |
| Level AA |
Intermediate (should have) |
Legal requirement in most jurisdictions |
wcag2aa, wcag21aa |
| Level AAA |
Advanced (nice to have) |
Not typically required |
wcag2aaa, wcag21aaa |
| Best Practice |
Industry recommendations |
Not WCAG but improves UX |
best-practice |
Axe-Core Tools Reference
AxeBuilder Configuration
| Method |
Purpose |
Example |
new AxeBuilder() |
Create scanner instance |
Entry point |
.withTags(List<String>) |
Filter by WCAG tags |
wcag2aa, wcag21aa |
.include(String) |
Scan specific selector |
#main-content |
.exclude(String) |
Skip selector from scan |
.third-party-widget |
.disableRules(List<String>) |
Disable specific rules |
color-contrast |
.withRules(List<String>) |
Run only specific rules |
label, button-name |
.analyze(WebDriver) |
Execute the scan |
Returns Results |
Results Object
| Method |
Returns |
Purpose |
getViolations() |
List<Rule> |
Rules that failed |
getPasses() |
List<Rule> |
Rules that passed |
getIncomplete() |
List<Rule> |
Rules needing manual review |
getInapplicable() |
List<Rule> |
Rules not applicable to page |
violationFree() |
boolean |
True if no violations |
Violation Impact Levels
| Impact |
Severity |
CI Action |
| Critical |
Blocks users completely |
Always fail build |
| Serious |
Significant barrier |
Always fail build |
| Moderate |
Some difficulty |
Warn or fail |
| Minor |
Inconvenience |
Log for review |
Core Capabilities
1. Axe Builder Analysis
- Full Page Scan:
new AxeBuilder().analyze(driver)
- Component Scan:
new AxeBuilder().include("#my-component").analyze(driver)
- Rule Configuration:
.withTags(List.of("wcag2a", "wcag2aa"))
- Exclusions:
.exclude(".legacy-footer") (use carefully, document reason)
2. Validation & Assertion
- Analyze
Results.getViolations() - should be empty
- Filter by impact level (Critical, Serious, Moderate, Minor)
- Use AssertJ Soft Assertions to report all violations before failing
3. Reporting
- Log: Rule ID + Help URL + Selector for each violation
- Serialize
Results to JSON for dashboards
- Attach to Allure reports
Your Role
As an Accessibility Automation Specialist:
- Integration: Configure axe-core with Selenium WebDriver
- Configuration: Set up
AxeBuilder with appropriate WCAG tags
- Analysis: Parse results to identify violations by impact
- Assertion: Fail on Critical/Serious, warn on Moderate/Minor
- Reporting: Log Help URLs and selectors for remediation
Step-by-Step Workflows
Workflow 1: Add A11y Scan to Existing Test
Add dependency to pom.xml
<dependency>
<groupId>com.deque.html.axe-core</groupId>
<artifactId>selenium</artifactId>
<version>4.10.0</version>
</dependency>
Create AccessibilityHelper utility
Add scan after page loads
driver.get("https://example.com");
waitForPageReady();
AccessibilityHelper.verifyPageAccessibility(driver);
Run and review violations
mvn test -Dtest=A11yTest
Workflow 2: Test Specific Component
Navigate to page with component visible
Trigger component state (open modal, show dropdown)
Scan only the component
Results results = new AxeBuilder()
.withTags(List.of("wcag2a", "wcag2aa"))
.include("#login-modal")
.analyze(driver);
Assert and log
Workflow 3: Keyboard Navigation Audit
- Identify all interactive elements
- Tab through the page programmatically
element.sendKeys(Keys.TAB);
WebElement focused = driver.switchTo().activeElement();
- Verify focus order is logical
- Test Escape closes modals
- Verify no keyboard traps
Workflow 4: CI Integration
Configure headless browser
mvn test -Dheadless=true -Dgroups=a11y
Set zero-tolerance for Critical/Serious
long criticalCount = violations.stream()
.filter(v -> List.of("critical", "serious").contains(v.getImpact()))
.count();
assertThat(criticalCount).isZero();
Generate JSON report for tracking
Code Patterns
Basic Full-Page Scan
@Step("Verify page accessibility - WCAG 2.1 AA")
public void verifyPageAccessibility(WebDriver driver) {
Results results = new AxeBuilder()
.withTags(List.of("wcag2a", "wcag2aa", "wcag21a", "wcag21aa"))
.analyze(driver);
logViolations(results.getViolations());
assertThat(results.violationFree())
.as("Accessibility violations found on: %s", driver.getCurrentUrl())
.isTrue();
}
Component-Specific Scan
@Step("Verify component accessibility: {selectors}")
public void verifyComponentAccessibility(WebDriver driver, String... selectors) {
AxeBuilder builder = new AxeBuilder()
.withTags(List.of("wcag2a", "wcag2aa"));
for (String selector : selectors) {
builder.include(selector);
}
Results results = builder.analyze(driver);
logViolations(results.getViolations());
assertThat(results.violationFree())
.as("Component accessibility check failed")
.isTrue();
}
Filter by Impact Level
@Step("Verify no critical accessibility violations")
public void verifyCriticalViolations(WebDriver driver) {
Results results = new AxeBuilder()
.withTags(List.of("wcag2a", "wcag2aa"))
.analyze(driver);
List<Rule> criticalViolations = results.getViolations().stream()
.filter(v -> List.of("critical", "serious").contains(v.getImpact()))
.toList();
if (!criticalViolations.isEmpty()) {
logViolations(criticalViolations);
}
assertThat(criticalViolations)
.as("Critical/Serious accessibility violations found")
.isEmpty();
}
With Documented Exclusions
/**
* Scan with exclusions for known issues.
* Exclusions must be documented with ticket reference.
*/
@Step("Verify accessibility with documented exclusions")
public void verifyWithExclusions(WebDriver driver) {
Results results = new AxeBuilder()
.withTags(List.of("wcag2a", "wcag2aa"))
.exclude(".third-party-chat-widget") // JIRA-1234: Vendor limitation
.exclude("#legacy-footer") // JIRA-5678: Scheduled for Q2 fix
.analyze(driver);
assertThat(results.violationFree()).isTrue();
}
Violation Logger
private void logViolations(List<Rule> violations) {
if (violations.isEmpty()) {
log.info("✓ No accessibility violations found");
return;
}
log.error("✗ Found {} accessibility violations:", violations.size());
for (Rule violation : violations) {
log.error(" [{}/{}] {}",
violation.getImpact().toUpperCase(),
violation.getId(),
violation.getDescription());
log.error(" Help: {}", violation.getHelpUrl());
for (CheckedNode node : violation.getNodes()) {
log.error(" Target: {}", String.join(", ", node.getTarget()));
log.error(" HTML: {}", truncate(node.getHtml(), 100));
}
}
}
JUnit 5 Test Class
@Epic("Accessibility")
@Feature("WCAG 2.1 AA Compliance")
class AccessibilityTest extends BaseTest {
@Test
@Tag("a11y")
@Severity(SeverityLevel.CRITICAL)
@DisplayName("Homepage should meet WCAG 2.1 AA standards")
void homePage_shouldBeAccessible() {
driver.get(ConfigReader.get("base.url"));
waitForPageReady();
Results results = new AxeBuilder()
.withTags(List.of("wcag2a", "wcag2aa", "wcag21a", "wcag21aa"))
.analyze(driver);
attachResultsToAllure(results);
SoftAssertions.assertSoftly(softly -> {
softly.assertThat(results.violationFree())
.as("Page should have no accessibility violations")
.isTrue();
});
}
@Test
@Tag("a11y")
@DisplayName("Login modal should be keyboard accessible")
void loginModal_shouldBeKeyboardAccessible() {
driver.get(ConfigReader.get("base.url"));
// Open modal
driver.findElement(By.id("login-btn")).click();
waitForVisible(By.id("login-modal"));
// Scan modal only
Results results = new AxeBuilder()
.withTags(List.of("wcag2a", "wcag2aa"))
.include("#login-modal")
.analyze(driver);
assertThat(results.violationFree()).isTrue();
// Test keyboard navigation
WebElement modal = driver.findElement(By.id("login-modal"));
WebElement firstInput = modal.findElement(By.cssSelector("input:first-of-type"));
assertThat(driver.switchTo().activeElement())
.as("Focus should be inside modal")
.isEqualTo(firstInput);
// Test Escape closes modal
modal.sendKeys(Keys.ESCAPE);
assertThat(isDisplayed(By.id("login-modal"))).isFalse();
}
}
Troubleshooting
| Problem |
Cause |
Solution |
| Axe returns empty results |
Page not fully loaded |
Add explicit wait for page ready state |
| False positives on contrast |
Dynamic themes |
Test both light and dark modes |
| Violations in third-party widgets |
Cannot modify vendor code |
Use .exclude() with documented ticket |
| Incomplete rules |
Requires manual review |
Log for manual audit, don't auto-fail |
| Different results between runs |
Async content loading |
Ensure deterministic page state before scan |
| CI fails but local passes |
Different viewport/browser |
Use same headless config as CI |
Best Practices Checklist
✅ Wait for page ready - Ensure DOM is stable before axe analysis
✅ Scan unique states - Test modal open, form error, empty state separately
✅ Zero tolerance for Critical/Serious - Always fail CI on these
✅ Use specific tags - Define wcag2aa vs best-practice to reduce noise
✅ Log Help URLs - Developers need the link to fix issues
✅ Document exclusions - Every .exclude() needs a JIRA ticket
✅ Test keyboard navigation - Tab order, focus traps, Escape key
✅ Attach JSON reports - Enable tracking violations over time
✅ Combine with manual audit - Axe catches ~30-50% of issues
Guardrails (Important Limitations)
⚠️ Automated tooling cannot prove full WCAG conformance - only the presence of certain issues
⚠️ Use automation to prevent regressions - use manual audits for complete coverage
⚠️ Prefer native HTML semantics - use ARIA only when required
⚠️ Never disable rules globally - scope exceptions narrowly with documentation
Triage by POUR Principles
| Principle |
Focus Areas |
Common Violations |
| Perceivable |
Text alternatives, captions, contrast, structure |
Missing alt text, low contrast, missing labels |
| Operable |
Keyboard access, focus order, bypass blocks |
Keyboard traps, no skip link, focus not visible |
| Understandable |
Labels, predictable behavior, error handling |
Unclear instructions, unexpected changes |
| Robust |
Valid HTML, ARIA, name/role/value |
Invalid ARIA, duplicate IDs, missing roles |
Running Tests
Maven Commands
| Command |
Purpose |
mvn test -Dgroups=a11y |
Run all accessibility tests |
mvn test -Dtest=A11yTest |
Run specific test class |
mvn test -Dheadless=true |
Run headless (CI mode) |
mvn allure:serve |
View Allure report with violations |
CI/CD Integration
- name: Run Accessibility Tests
run: mvn test -Dgroups=a11y -Dheadless=true
- name: Upload A11y Report
uses: actions/upload-artifact@v3
with:
name: a11y-report
path: target/a11y-results/
Common Rationalizations
Common shortcuts and "good enough" excuses that erode test quality — and the reality behind each.
| Rationalization |
Reality |
| "Selenium isn't good for a11y testing" |
axe-core + Selenium is battle-tested, CI-ready, and covers WCAG violations programmatically. |
| "We can just run a scan at the end" |
Shift-left: catch violations as code is written. Late scans mean expensive fixes. |
| "The framework handles accessibility" |
No framework auto-generates proper ARIA roles, labels, or keyboard interactions. |
| "We only need to test the homepage" |
Every page a user visits must be accessible. Start with high-risk pages, expand coverage. |
| "Skip the contrast checks, designers fix that" |
Automated contrast checks take seconds and prevent lawsuits. They are tests, not design reviews. |
| "Our users don't have disabilities" |
~15% of the global population has some form of disability. Accessibility is for everyone. |
References
Quick Reference
| Task |
Code Pattern |
| Full page scan |
new AxeBuilder().withTags(List.of("wcag2aa")).analyze(driver) |
| Component scan |
new AxeBuilder().include("#selector").analyze(driver) |
| Exclude element |
new AxeBuilder().exclude(".ignore").analyze(driver) |
| Check violations |
results.getViolations().isEmpty() |
| Filter critical |
.filter(v -> v.getImpact().equals("critical")) |
| Get help URL |
violation.getHelpUrl() |
| Tab navigation |
element.sendKeys(Keys.TAB) |
| Get focused element |
driver.switchTo().activeElement() |
Verification
After completing this skill's workflow, confirm:
1---2name: accessibility-selenium-testing3description: Accessibility testing toolkit using Selenium WebDriver 4+ with Java 21+ and axe-core engine. Use when asked to validate WCAG 2.1/2.2 compliance, scan pages or components for a11y violations, test keyboard navigation, audit color contrast, check ARIA semantics, generate accessibility reports, filter axe rules, debug screen reader issues, or implement POUR principles (perceivable, operable, understandable, robust).4---56# Accessibility Testing with Selenium WebDriver & Axe Core78This skill enables automated accessibility analysis within the Selenium WebDriver framework using the **axe-core** engine to detect WCAG violations and best practice issues directly in the browser.910> **Activation:** This skill is triggered when you need to validate WCAG compliance, scan for accessibility violations, test keyboard navigation, audit ARIA semantics, or generate a11y reports.1112## First Questions to Ask1314- What app URL(s) or user flows are in scope (and what is explicitly out of scope)?15- Is there an existing Selenium setup and how is CI run?16- Which standard is the target (WCAG 2.1 AA by default), and are there org-specific policies?17- Which pages/components are highest risk (auth, checkout, forms, modals, navigation)?18- Are there known constraints (legacy markup, third-party widgets) that require exceptions?1920## Prerequisites2122| Component | Version | Purpose |23|-----------|---------|---------|24| Java JDK | 21+ | Runtime with modern features |25| Maven | 3.9+ | Dependency management |26| Selenium WebDriver | 4.x | Browser automation |27| axe-core-selenium | 4.10+ | Deque axe-core integration |28| JUnit 5 | 5.10+ | Test framework |29| AssertJ | 3.x | Fluent assertions for readable failures |30| Allure | 2.x | Reporting with a11y violation attachments |3132> **Note:** Use `com.deque.html.axe-core:selenium` Maven dependency for axe integration.3334---3536## WCAG Compliance Levels3738| Level | Requirement | Legal Status | Axe Tags |39|-------|-------------|--------------|----------|40| **Level A** | Basic accessibility (must have) | Minimum legal requirement | `wcag2a`, `wcag21a` |41| **Level AA** | Intermediate (should have) | Legal requirement in most jurisdictions | `wcag2aa`, `wcag21aa` |42| **Level AAA** | Advanced (nice to have) | Not typically required | `wcag2aaa`, `wcag21aaa` |43| **Best Practice** | Industry recommendations | Not WCAG but improves UX | `best-practice` |4445---4647## Axe-Core Tools Reference4849### AxeBuilder Configuration5051| Method | Purpose | Example |52|--------|---------|---------|53| `new AxeBuilder()` | Create scanner instance | Entry point |54| `.withTags(List<String>)` | Filter by WCAG tags | `wcag2aa`, `wcag21aa` |55| `.include(String)` | Scan specific selector | `#main-content` |56| `.exclude(String)` | Skip selector from scan | `.third-party-widget` |57| `.disableRules(List<String>)` | Disable specific rules | `color-contrast` |58| `.withRules(List<String>)` | Run only specific rules | `label`, `button-name` |59| `.analyze(WebDriver)` | Execute the scan | Returns `Results` |6061### Results Object6263| Method | Returns | Purpose |64|--------|---------|---------|65| `getViolations()` | `List<Rule>` | Rules that failed |66| `getPasses()` | `List<Rule>` | Rules that passed |67| `getIncomplete()` | `List<Rule>` | Rules needing manual review |68| `getInapplicable()` | `List<Rule>` | Rules not applicable to page |69| `violationFree()` | `boolean` | True if no violations |7071### Violation Impact Levels7273| Impact | Severity | CI Action |74|--------|----------|-----------|75| **Critical** | Blocks users completely | Always fail build |76| **Serious** | Significant barrier | Always fail build |77| **Moderate** | Some difficulty | Warn or fail |78| **Minor** | Inconvenience | Log for review |7980---8182## Core Capabilities8384### 1. Axe Builder Analysis85- **Full Page Scan**: `new AxeBuilder().analyze(driver)`86- **Component Scan**: `new AxeBuilder().include("#my-component").analyze(driver)`87- **Rule Configuration**: `.withTags(List.of("wcag2a", "wcag2aa"))`88- **Exclusions**: `.exclude(".legacy-footer")` (use carefully, document reason)8990### 2. Validation & Assertion91- Analyze `Results.getViolations()` - should be empty92- Filter by impact level (Critical, Serious, Moderate, Minor)93- Use AssertJ Soft Assertions to report all violations before failing9495### 3. Reporting96- Log: Rule ID + Help URL + Selector for each violation97- Serialize `Results` to JSON for dashboards98- Attach to Allure reports99100---101102## Your Role103104As an Accessibility Automation Specialist:1051061. **Integration**: Configure axe-core with Selenium WebDriver1072. **Configuration**: Set up `AxeBuilder` with appropriate WCAG tags1083. **Analysis**: Parse results to identify violations by impact1094. **Assertion**: Fail on Critical/Serious, warn on Moderate/Minor1105. **Reporting**: Log Help URLs and selectors for remediation111112---113114## Step-by-Step Workflows115116### Workflow 1: Add A11y Scan to Existing Test1171181. **Add dependency to pom.xml**119 ```xml120 <dependency>121 <groupId>com.deque.html.axe-core</groupId>122 <artifactId>selenium</artifactId>123 <version>4.10.0</version>124 </dependency>125 ```1261272. **Create AccessibilityHelper utility**128 - See [Axe Patterns Guide](references/axe_patterns.md)1291303. **Add scan after page loads**131 ```java132 driver.get("https://example.com");133 waitForPageReady();134 AccessibilityHelper.verifyPageAccessibility(driver);135 ```1361374. **Run and review violations**138 ```bash139 mvn test -Dtest=A11yTest140 ```141142### Workflow 2: Test Specific Component1431441. **Navigate to page with component visible**1452. **Trigger component state** (open modal, show dropdown)1463. **Scan only the component**147 ```java148 Results results = new AxeBuilder()149 .withTags(List.of("wcag2a", "wcag2aa"))150 .include("#login-modal")151 .analyze(driver);152 ```1531544. **Assert and log**155156### Workflow 3: Keyboard Navigation Audit1571581. **Identify all interactive elements**1592. **Tab through the page programmatically**160 ```java161 element.sendKeys(Keys.TAB);162 WebElement focused = driver.switchTo().activeElement();163 ```1643. **Verify focus order is logical**1654. **Test Escape closes modals**1665. **Verify no keyboard traps**167168### Workflow 4: CI Integration1691701. **Configure headless browser**171 ```bash172 mvn test -Dheadless=true -Dgroups=a11y173 ```1741752. **Set zero-tolerance for Critical/Serious**176 ```java177 long criticalCount = violations.stream()178 .filter(v -> List.of("critical", "serious").contains(v.getImpact()))179 .count();180 assertThat(criticalCount).isZero();181 ```1821833. **Generate JSON report for tracking**184185---186187## Code Patterns188189### Basic Full-Page Scan190191```java192@Step("Verify page accessibility - WCAG 2.1 AA")193public void verifyPageAccessibility(WebDriver driver) {194 Results results = new AxeBuilder()195 .withTags(List.of("wcag2a", "wcag2aa", "wcag21a", "wcag21aa"))196 .analyze(driver);197198 logViolations(results.getViolations());199200 assertThat(results.violationFree())201 .as("Accessibility violations found on: %s", driver.getCurrentUrl())202 .isTrue();203}204```205206### Component-Specific Scan207208```java209@Step("Verify component accessibility: {selectors}")210public void verifyComponentAccessibility(WebDriver driver, String... selectors) {211 AxeBuilder builder = new AxeBuilder()212 .withTags(List.of("wcag2a", "wcag2aa"));213214 for (String selector : selectors) {215 builder.include(selector);216 }217218 Results results = builder.analyze(driver);219 logViolations(results.getViolations());220221 assertThat(results.violationFree())222 .as("Component accessibility check failed")223 .isTrue();224}225```226227### Filter by Impact Level228229```java230@Step("Verify no critical accessibility violations")231public void verifyCriticalViolations(WebDriver driver) {232 Results results = new AxeBuilder()233 .withTags(List.of("wcag2a", "wcag2aa"))234 .analyze(driver);235236 List<Rule> criticalViolations = results.getViolations().stream()237 .filter(v -> List.of("critical", "serious").contains(v.getImpact()))238 .toList();239240 if (!criticalViolations.isEmpty()) {241 logViolations(criticalViolations);242 }243244 assertThat(criticalViolations)245 .as("Critical/Serious accessibility violations found")246 .isEmpty();247}248```249250### With Documented Exclusions251252```java253/**254 * Scan with exclusions for known issues.255 * Exclusions must be documented with ticket reference.256 */257@Step("Verify accessibility with documented exclusions")258public void verifyWithExclusions(WebDriver driver) {259 Results results = new AxeBuilder()260 .withTags(List.of("wcag2a", "wcag2aa"))261 .exclude(".third-party-chat-widget") // JIRA-1234: Vendor limitation262 .exclude("#legacy-footer") // JIRA-5678: Scheduled for Q2 fix263 .analyze(driver);264265 assertThat(results.violationFree()).isTrue();266}267```268269### Violation Logger270271```java272private void logViolations(List<Rule> violations) {273 if (violations.isEmpty()) {274 log.info("✓ No accessibility violations found");275 return;276 }277278 log.error("✗ Found {} accessibility violations:", violations.size());279 for (Rule violation : violations) {280 log.error(" [{}/{}] {}",281 violation.getImpact().toUpperCase(),282 violation.getId(),283 violation.getDescription());284 log.error(" Help: {}", violation.getHelpUrl());285286 for (CheckedNode node : violation.getNodes()) {287 log.error(" Target: {}", String.join(", ", node.getTarget()));288 log.error(" HTML: {}", truncate(node.getHtml(), 100));289 }290 }291}292```293294### JUnit 5 Test Class295296```java297@Epic("Accessibility")298@Feature("WCAG 2.1 AA Compliance")299class AccessibilityTest extends BaseTest {300301 @Test302 @Tag("a11y")303 @Severity(SeverityLevel.CRITICAL)304 @DisplayName("Homepage should meet WCAG 2.1 AA standards")305 void homePage_shouldBeAccessible() {306 driver.get(ConfigReader.get("base.url"));307 waitForPageReady();308309 Results results = new AxeBuilder()310 .withTags(List.of("wcag2a", "wcag2aa", "wcag21a", "wcag21aa"))311 .analyze(driver);312313 attachResultsToAllure(results);314315 SoftAssertions.assertSoftly(softly -> {316 softly.assertThat(results.violationFree())317 .as("Page should have no accessibility violations")318 .isTrue();319 });320 }321322 @Test323 @Tag("a11y")324 @DisplayName("Login modal should be keyboard accessible")325 void loginModal_shouldBeKeyboardAccessible() {326 driver.get(ConfigReader.get("base.url"));327328 // Open modal329 driver.findElement(By.id("login-btn")).click();330 waitForVisible(By.id("login-modal"));331332 // Scan modal only333 Results results = new AxeBuilder()334 .withTags(List.of("wcag2a", "wcag2aa"))335 .include("#login-modal")336 .analyze(driver);337338 assertThat(results.violationFree()).isTrue();339340 // Test keyboard navigation341 WebElement modal = driver.findElement(By.id("login-modal"));342 WebElement firstInput = modal.findElement(By.cssSelector("input:first-of-type"));343344 assertThat(driver.switchTo().activeElement())345 .as("Focus should be inside modal")346 .isEqualTo(firstInput);347348 // Test Escape closes modal349 modal.sendKeys(Keys.ESCAPE);350 assertThat(isDisplayed(By.id("login-modal"))).isFalse();351 }352}353```354355---356357## Troubleshooting358359| Problem | Cause | Solution |360|---------|-------|----------|361| Axe returns empty results | Page not fully loaded | Add explicit wait for page ready state |362| False positives on contrast | Dynamic themes | Test both light and dark modes |363| Violations in third-party widgets | Cannot modify vendor code | Use `.exclude()` with documented ticket |364| Incomplete rules | Requires manual review | Log for manual audit, don't auto-fail |365| Different results between runs | Async content loading | Ensure deterministic page state before scan |366| CI fails but local passes | Different viewport/browser | Use same headless config as CI |367368---369370## Best Practices Checklist371372✅ **Wait for page ready** - Ensure DOM is stable before axe analysis373✅ **Scan unique states** - Test modal open, form error, empty state separately374✅ **Zero tolerance for Critical/Serious** - Always fail CI on these375✅ **Use specific tags** - Define `wcag2aa` vs `best-practice` to reduce noise376✅ **Log Help URLs** - Developers need the link to fix issues377✅ **Document exclusions** - Every `.exclude()` needs a JIRA ticket378✅ **Test keyboard navigation** - Tab order, focus traps, Escape key379✅ **Attach JSON reports** - Enable tracking violations over time380✅ **Combine with manual audit** - Axe catches ~30-50% of issues381382---383384## Guardrails (Important Limitations)385386⚠️ **Automated tooling cannot prove full WCAG conformance** - only the presence of certain issues387⚠️ **Use automation to prevent regressions** - use manual audits for complete coverage388⚠️ **Prefer native HTML semantics** - use ARIA only when required389⚠️ **Never disable rules globally** - scope exceptions narrowly with documentation390391---392393## Triage by POUR Principles394395| Principle | Focus Areas | Common Violations |396|-----------|-------------|-------------------|397| **Perceivable** | Text alternatives, captions, contrast, structure | Missing alt text, low contrast, missing labels |398| **Operable** | Keyboard access, focus order, bypass blocks | Keyboard traps, no skip link, focus not visible |399| **Understandable** | Labels, predictable behavior, error handling | Unclear instructions, unexpected changes |400| **Robust** | Valid HTML, ARIA, name/role/value | Invalid ARIA, duplicate IDs, missing roles |401402---403404## Running Tests405406### Maven Commands407408| Command | Purpose |409|---------|---------|410| `mvn test -Dgroups=a11y` | Run all accessibility tests |411| `mvn test -Dtest=A11yTest` | Run specific test class |412| `mvn test -Dheadless=true` | Run headless (CI mode) |413| `mvn allure:serve` | View Allure report with violations |414415### CI/CD Integration416417```yaml418- name: Run Accessibility Tests419 run: mvn test -Dgroups=a11y -Dheadless=true420421- name: Upload A11y Report422 uses: actions/upload-artifact@v3423 with:424 name: a11y-report425 path: target/a11y-results/426```427428---429430## Common Rationalizations431432> Common shortcuts and "good enough" excuses that erode test quality — and the reality behind each.433434| Rationalization | Reality |435| --------------- | ------- |436| "Selenium isn't good for a11y testing" | axe-core + Selenium is battle-tested, CI-ready, and covers WCAG violations programmatically. |437| "We can just run a scan at the end" | Shift-left: catch violations as code is written. Late scans mean expensive fixes. |438| "The framework handles accessibility" | No framework auto-generates proper ARIA roles, labels, or keyboard interactions. |439| "We only need to test the homepage" | Every page a user visits must be accessible. Start with high-risk pages, expand coverage. |440| "Skip the contrast checks, designers fix that" | Automated contrast checks take seconds and prevent lawsuits. They are tests, not design reviews. |441| "Our users don't have disabilities" | ~15% of the global population has some form of disability. Accessibility is for everyone. |442443---444445## References446447- [Axe Patterns Guide](references/axe_patterns.md) - AxeBuilder patterns and helpers448- [WCAG 2.1 AA Checklist](references/wcag21aa-checklist.md) - Manual audit checklist449- [Deque Axe Rules](https://dequeuniversity.com/rules/axe/4.10) - Rule descriptions450- [W3C WCAG 2.1](https://www.w3.org/TR/WCAG21/) - Official specification451- [WAI-ARIA Practices](https://www.w3.org/WAI/ARIA/apg/) - Widget patterns452453---454455## Quick Reference456457| Task | Code Pattern |458|------|--------------|459| Full page scan | `new AxeBuilder().withTags(List.of("wcag2aa")).analyze(driver)` |460| Component scan | `new AxeBuilder().include("#selector").analyze(driver)` |461| Exclude element | `new AxeBuilder().exclude(".ignore").analyze(driver)` |462| Check violations | `results.getViolations().isEmpty()` |463| Filter critical | `.filter(v -> v.getImpact().equals("critical"))` |464| Get help URL | `violation.getHelpUrl()` |465| Tab navigation | `element.sendKeys(Keys.TAB)` |466| Get focused element | `driver.switchTo().activeElement()` |467468---469470## Verification471472After completing this skill's workflow, confirm:473474- [ ] **Axe WebDriver audit passes** — `AxeBuilder.analyze(driver)` returns zero violations475- [ ] **WCAG 2.1 AA compliance** — All rules for AA level pass476- [ ] **ARIA labels present** — All interactive elements have accessible names477- [ ] **Keyboard accessibility verified** — Tab navigation reaches all interactive elements478- [ ] **Violation report saved** — Accessibility results written to JSON/HTML file479- [ ] **Tests pass with Java 21+** — `mvn test -Dtest=*Accessibility*` passes