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-testing
3description: 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).
4metadata:
5 source: https://skillmd.com/skills/aibot88/accessibility-selenium-testing
6---
7
8# Accessibility Testing with Selenium WebDriver & Axe Core
9
10This 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.
11
12> **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.
13
14## First Questions to Ask
15
16- What app URL(s) or user flows are in scope (and what is explicitly out of scope)?
17- Is there an existing Selenium setup and how is CI run?
18- Which standard is the target (WCAG 2.1 AA by default), and are there org-specific policies?
19- Which pages/components are highest risk (auth, checkout, forms, modals, navigation)?
20- Are there known constraints (legacy markup, third-party widgets) that require exceptions?
21
22## Prerequisites
23
24| Component | Version | Purpose |
25|-----------|---------|---------|
26| Java JDK | 21+ | Runtime with modern features |
27| Maven | 3.9+ | Dependency management |
28| Selenium WebDriver | 4.x | Browser automation |
29| axe-core-selenium | 4.10+ | Deque axe-core integration |
30| JUnit 5 | 5.10+ | Test framework |
31| AssertJ | 3.x | Fluent assertions for readable failures |
32| Allure | 2.x | Reporting with a11y violation attachments |
33
34> **Note:** Use `com.deque.html.axe-core:selenium` Maven dependency for axe integration.
35
36---
37
38## WCAG Compliance Levels
39
40| Level | Requirement | Legal Status | Axe Tags |
41|-------|-------------|--------------|----------|
42| **Level A** | Basic accessibility (must have) | Minimum legal requirement | `wcag2a`, `wcag21a` |
43| **Level AA** | Intermediate (should have) | Legal requirement in most jurisdictions | `wcag2aa`, `wcag21aa` |
44| **Level AAA** | Advanced (nice to have) | Not typically required | `wcag2aaa`, `wcag21aaa` |
45| **Best Practice** | Industry recommendations | Not WCAG but improves UX | `best-practice` |
46
47---
48
49## Axe-Core Tools Reference
50
51### AxeBuilder Configuration
52
53| Method | Purpose | Example |
54|--------|---------|---------|
55| `new AxeBuilder()` | Create scanner instance | Entry point |
56| `.withTags(List<String>)` | Filter by WCAG tags | `wcag2aa`, `wcag21aa` |
57| `.include(String)` | Scan specific selector | `#main-content` |
58| `.exclude(String)` | Skip selector from scan | `.third-party-widget` |
59| `.disableRules(List<String>)` | Disable specific rules | `color-contrast` |
60| `.withRules(List<String>)` | Run only specific rules | `label`, `button-name` |
61| `.analyze(WebDriver)` | Execute the scan | Returns `Results` |
62
63### Results Object
64
65| Method | Returns | Purpose |
66|--------|---------|---------|
67| `getViolations()` | `List<Rule>` | Rules that failed |
68| `getPasses()` | `List<Rule>` | Rules that passed |
69| `getIncomplete()` | `List<Rule>` | Rules needing manual review |
70| `getInapplicable()` | `List<Rule>` | Rules not applicable to page |
71| `violationFree()` | `boolean` | True if no violations |
72
73### Violation Impact Levels
74
75| Impact | Severity | CI Action |
76|--------|----------|-----------|
77| **Critical** | Blocks users completely | Always fail build |
78| **Serious** | Significant barrier | Always fail build |
79| **Moderate** | Some difficulty | Warn or fail |
80| **Minor** | Inconvenience | Log for review |
81
82---
83
84## Core Capabilities
85
86### 1. Axe Builder Analysis
87- **Full Page Scan**: `new AxeBuilder().analyze(driver)`
88- **Component Scan**: `new AxeBuilder().include("#my-component").analyze(driver)`
89- **Rule Configuration**: `.withTags(List.of("wcag2a", "wcag2aa"))`
90- **Exclusions**: `.exclude(".legacy-footer")` (use carefully, document reason)
91
92### 2. Validation & Assertion
93- Analyze `Results.getViolations()` - should be empty
94- Filter by impact level (Critical, Serious, Moderate, Minor)
95- Use AssertJ Soft Assertions to report all violations before failing
96
97### 3. Reporting
98- Log: Rule ID + Help URL + Selector for each violation
99- Serialize `Results` to JSON for dashboards
100- Attach to Allure reports
101
102---
103
104## Your Role
105
106As an Accessibility Automation Specialist:
107
1081. **Integration**: Configure axe-core with Selenium WebDriver
1092. **Configuration**: Set up `AxeBuilder` with appropriate WCAG tags
1103. **Analysis**: Parse results to identify violations by impact
1114. **Assertion**: Fail on Critical/Serious, warn on Moderate/Minor
1125. **Reporting**: Log Help URLs and selectors for remediation
113
114---
115
116## Step-by-Step Workflows
117
118### Workflow 1: Add A11y Scan to Existing Test
119
1201. **Add dependency to pom.xml**
121 ```xml
122 <dependency>
123 <groupId>com.deque.html.axe-core</groupId>
124 <artifactId>selenium</artifactId>
125 <version>4.10.0</version>
126 </dependency>
127 ```
128
1292. **Create AccessibilityHelper utility**
130 - See [Axe Patterns Guide](references/axe_patterns.md)
131
1323. **Add scan after page loads**
133 ```java
134 driver.get("https://example.com");
135 waitForPageReady();
136 AccessibilityHelper.verifyPageAccessibility(driver);
137 ```
138
1394. **Run and review violations**
140 ```bash
141 mvn test -Dtest=A11yTest
142 ```
143
144### Workflow 2: Test Specific Component
145
1461. **Navigate to page with component visible**
1472. **Trigger component state** (open modal, show dropdown)
1483. **Scan only the component**
149 ```java
150 Results results = new AxeBuilder()
151 .withTags(List.of("wcag2a", "wcag2aa"))
152 .include("#login-modal")
153 .analyze(driver);
154 ```
155
1564. **Assert and log**
157
158### Workflow 3: Keyboard Navigation Audit
159
1601. **Identify all interactive elements**
1612. **Tab through the page programmatically**
162 ```java
163 element.sendKeys(Keys.TAB);
164 WebElement focused = driver.switchTo().activeElement();
165 ```
1663. **Verify focus order is logical**
1674. **Test Escape closes modals**
1685. **Verify no keyboard traps**
169
170### Workflow 4: CI Integration
171
1721. **Configure headless browser**
173 ```bash
174 mvn test -Dheadless=true -Dgroups=a11y
175 ```
176
1772. **Set zero-tolerance for Critical/Serious**
178 ```java
179 long criticalCount = violations.stream()
180 .filter(v -> List.of("critical", "serious").contains(v.getImpact()))
181 .count();
182 assertThat(criticalCount).isZero();
183 ```
184
1853. **Generate JSON report for tracking**
186
187---
188
189## Code Patterns
190
191### Basic Full-Page Scan
192
193```java
194@Step("Verify page accessibility - WCAG 2.1 AA")
195public void verifyPageAccessibility(WebDriver driver) {
196 Results results = new AxeBuilder()
197 .withTags(List.of("wcag2a", "wcag2aa", "wcag21a", "wcag21aa"))
198 .analyze(driver);
199
200 logViolations(results.getViolations());
201
202 assertThat(results.violationFree())
203 .as("Accessibility violations found on: %s", driver.getCurrentUrl())
204 .isTrue();
205}
206```
207
208### Component-Specific Scan
209
210```java
211@Step("Verify component accessibility: {selectors}")
212public void verifyComponentAccessibility(WebDriver driver, String... selectors) {
213 AxeBuilder builder = new AxeBuilder()
214 .withTags(List.of("wcag2a", "wcag2aa"));
215
216 for (String selector : selectors) {
217 builder.include(selector);
218 }
219
220 Results results = builder.analyze(driver);
221 logViolations(results.getViolations());
222
223 assertThat(results.violationFree())
224 .as("Component accessibility check failed")
225 .isTrue();
226}
227```
228
229### Filter by Impact Level
230
231```java
232@Step("Verify no critical accessibility violations")
233public void verifyCriticalViolations(WebDriver driver) {
234 Results results = new AxeBuilder()
235 .withTags(List.of("wcag2a", "wcag2aa"))
236 .analyze(driver);
237
238 List<Rule> criticalViolations = results.getViolations().stream()
239 .filter(v -> List.of("critical", "serious").contains(v.getImpact()))
240 .toList();
241
242 if (!criticalViolations.isEmpty()) {
243 logViolations(criticalViolations);
244 }
245
246 assertThat(criticalViolations)
247 .as("Critical/Serious accessibility violations found")
248 .isEmpty();
249}
250```
251
252### With Documented Exclusions
253
254```java
255/**
256 * Scan with exclusions for known issues.
257 * Exclusions must be documented with ticket reference.
258 */
259@Step("Verify accessibility with documented exclusions")
260public void verifyWithExclusions(WebDriver driver) {
261 Results results = new AxeBuilder()
262 .withTags(List.of("wcag2a", "wcag2aa"))
263 .exclude(".third-party-chat-widget") // JIRA-1234: Vendor limitation
264 .exclude("#legacy-footer") // JIRA-5678: Scheduled for Q2 fix
265 .analyze(driver);
266
267 assertThat(results.violationFree()).isTrue();
268}
269```
270
271### Violation Logger
272
273```java
274private void logViolations(List<Rule> violations) {
275 if (violations.isEmpty()) {
276 log.info("✓ No accessibility violations found");
277 return;
278 }
279
280 log.error("✗ Found {} accessibility violations:", violations.size());
281 for (Rule violation : violations) {
282 log.error(" [{}/{}] {}",
283 violation.getImpact().toUpperCase(),
284 violation.getId(),
285 violation.getDescription());
286 log.error(" Help: {}", violation.getHelpUrl());
287
288 for (CheckedNode node : violation.getNodes()) {
289 log.error(" Target: {}", String.join(", ", node.getTarget()));
290 log.error(" HTML: {}", truncate(node.getHtml(), 100));
291 }
292 }
293}
294```
295
296### JUnit 5 Test Class
297
298```java
299@Epic("Accessibility")
300@Feature("WCAG 2.1 AA Compliance")
301class AccessibilityTest extends BaseTest {
302
303 @Test
304 @Tag("a11y")
305 @Severity(SeverityLevel.CRITICAL)
306 @DisplayName("Homepage should meet WCAG 2.1 AA standards")
307 void homePage_shouldBeAccessible() {
308 driver.get(ConfigReader.get("base.url"));
309 waitForPageReady();
310
311 Results results = new AxeBuilder()
312 .withTags(List.of("wcag2a", "wcag2aa", "wcag21a", "wcag21aa"))
313 .analyze(driver);
314
315 attachResultsToAllure(results);
316
317 SoftAssertions.assertSoftly(softly -> {
318 softly.assertThat(results.violationFree())
319 .as("Page should have no accessibility violations")
320 .isTrue();
321 });
322 }
323
324 @Test
325 @Tag("a11y")
326 @DisplayName("Login modal should be keyboard accessible")
327 void loginModal_shouldBeKeyboardAccessible() {
328 driver.get(ConfigReader.get("base.url"));
329
330 // Open modal
331 driver.findElement(By.id("login-btn")).click();
332 waitForVisible(By.id("login-modal"));
333
334 // Scan modal only
335 Results results = new AxeBuilder()
336 .withTags(List.of("wcag2a", "wcag2aa"))
337 .include("#login-modal")
338 .analyze(driver);
339
340 assertThat(results.violationFree()).isTrue();
341
342 // Test keyboard navigation
343 WebElement modal = driver.findElement(By.id("login-modal"));
344 WebElement firstInput = modal.findElement(By.cssSelector("input:first-of-type"));
345
346 assertThat(driver.switchTo().activeElement())
347 .as("Focus should be inside modal")
348 .isEqualTo(firstInput);
349
350 // Test Escape closes modal
351 modal.sendKeys(Keys.ESCAPE);
352 assertThat(isDisplayed(By.id("login-modal"))).isFalse();
353 }
354}
355```
356
357---
358
359## Troubleshooting
360
361| Problem | Cause | Solution |
362|---------|-------|----------|
363| Axe returns empty results | Page not fully loaded | Add explicit wait for page ready state |
364| False positives on contrast | Dynamic themes | Test both light and dark modes |
365| Violations in third-party widgets | Cannot modify vendor code | Use `.exclude()` with documented ticket |
366| Incomplete rules | Requires manual review | Log for manual audit, don't auto-fail |
367| Different results between runs | Async content loading | Ensure deterministic page state before scan |
368| CI fails but local passes | Different viewport/browser | Use same headless config as CI |
369
370---
371
372## Best Practices Checklist
373
374✅ **Wait for page ready** - Ensure DOM is stable before axe analysis
375✅ **Scan unique states** - Test modal open, form error, empty state separately
376✅ **Zero tolerance for Critical/Serious** - Always fail CI on these
377✅ **Use specific tags** - Define `wcag2aa` vs `best-practice` to reduce noise
378✅ **Log Help URLs** - Developers need the link to fix issues
379✅ **Document exclusions** - Every `.exclude()` needs a JIRA ticket
380✅ **Test keyboard navigation** - Tab order, focus traps, Escape key
381✅ **Attach JSON reports** - Enable tracking violations over time
382✅ **Combine with manual audit** - Axe catches ~30-50% of issues
383
384---
385
386## Guardrails (Important Limitations)
387
388⚠️ **Automated tooling cannot prove full WCAG conformance** - only the presence of certain issues
389⚠️ **Use automation to prevent regressions** - use manual audits for complete coverage
390⚠️ **Prefer native HTML semantics** - use ARIA only when required
391⚠️ **Never disable rules globally** - scope exceptions narrowly with documentation
392
393---
394
395## Triage by POUR Principles
396
397| Principle | Focus Areas | Common Violations |
398|-----------|-------------|-------------------|
399| **Perceivable** | Text alternatives, captions, contrast, structure | Missing alt text, low contrast, missing labels |
400| **Operable** | Keyboard access, focus order, bypass blocks | Keyboard traps, no skip link, focus not visible |
401| **Understandable** | Labels, predictable behavior, error handling | Unclear instructions, unexpected changes |
402| **Robust** | Valid HTML, ARIA, name/role/value | Invalid ARIA, duplicate IDs, missing roles |
403
404---
405
406## Running Tests
407
408### Maven Commands
409
410| Command | Purpose |
411|---------|---------|
412| `mvn test -Dgroups=a11y` | Run all accessibility tests |
413| `mvn test -Dtest=A11yTest` | Run specific test class |
414| `mvn test -Dheadless=true` | Run headless (CI mode) |
415| `mvn allure:serve` | View Allure report with violations |
416
417### CI/CD Integration
418
419```yaml
420- name: Run Accessibility Tests
421 run: mvn test -Dgroups=a11y -Dheadless=true
422
423- name: Upload A11y Report
424 uses: actions/upload-artifact@v3
425 with:
426 name: a11y-report
427 path: target/a11y-results/
428```
429
430---
431
432## Common Rationalizations
433
434> Common shortcuts and "good enough" excuses that erode test quality — and the reality behind each.
435
436| Rationalization | Reality |
437| --------------- | ------- |
438| "Selenium isn't good for a11y testing" | axe-core + Selenium is battle-tested, CI-ready, and covers WCAG violations programmatically. |
439| "We can just run a scan at the end" | Shift-left: catch violations as code is written. Late scans mean expensive fixes. |
440| "The framework handles accessibility" | No framework auto-generates proper ARIA roles, labels, or keyboard interactions. |
441| "We only need to test the homepage" | Every page a user visits must be accessible. Start with high-risk pages, expand coverage. |
442| "Skip the contrast checks, designers fix that" | Automated contrast checks take seconds and prevent lawsuits. They are tests, not design reviews. |
443| "Our users don't have disabilities" | ~15% of the global population has some form of disability. Accessibility is for everyone. |
444
445---
446
447## References
448
449- [Axe Patterns Guide](references/axe_patterns.md) - AxeBuilder patterns and helpers
450- [WCAG 2.1 AA Checklist](references/wcag21aa-checklist.md) - Manual audit checklist
451- [Deque Axe Rules](https://dequeuniversity.com/rules/axe/4.10) - Rule descriptions
452- [W3C WCAG 2.1](https://www.w3.org/TR/WCAG21/) - Official specification
453- [WAI-ARIA Practices](https://www.w3.org/WAI/ARIA/apg/) - Widget patterns
454
455---
456
457## Quick Reference
458
459| Task | Code Pattern |
460|------|--------------|
461| Full page scan | `new AxeBuilder().withTags(List.of("wcag2aa")).analyze(driver)` |
462| Component scan | `new AxeBuilder().include("#selector").analyze(driver)` |
463| Exclude element | `new AxeBuilder().exclude(".ignore").analyze(driver)` |
464| Check violations | `results.getViolations().isEmpty()` |
465| Filter critical | `.filter(v -> v.getImpact().equals("critical"))` |
466| Get help URL | `violation.getHelpUrl()` |
467| Tab navigation | `element.sendKeys(Keys.TAB)` |
468| Get focused element | `driver.switchTo().activeElement()` |
469
470---
471
472## Verification
473
474After completing this skill's workflow, confirm:
475
476- [ ] **Axe WebDriver audit passes** — `AxeBuilder.analyze(driver)` returns zero violations
477- [ ] **WCAG 2.1 AA compliance** — All rules for AA level pass
478- [ ] **ARIA labels present** — All interactive elements have accessible names
479- [ ] **Keyboard accessibility verified** — Tab navigation reaches all interactive elements
480- [ ] **Violation report saved** — Accessibility results written to JSON/HTML file
481- [ ] **Tests pass with Java 21+** — `mvn test -Dtest=*Accessibility*` passes