Accordion
A vertically stacked set of interactive headings that each reveal a section of content.
Demo
Single Expansion (Default)
Only one panel can be expanded at a time. Opening a new panel closes the previously open one.
Multiple Expansion
Multiple panels can be expanded simultaneously using the allowMultiple
prop.
With Disabled Items
Individual accordion items can be disabled. Keyboard navigation automatically skips disabled items.
Accessibility Features
WAI-ARIA Roles
| Role | Target Element | Description |
|---|---|---|
heading | Header wrapper (h2-h6) | Contains the accordion trigger button |
button | Header trigger | Interactive element that toggles panel visibility |
region | Panel (optional) | Content area associated with header (omit for 6+ panels) |
WAI-ARIA Properties
aria-level
headingLevel prop
- Values
- 2 - 6
- Required
- Yes
aria-controls
Auto-generated
- Values
- ID reference to associated panel
- Required
- Yes
aria-labelledby
Auto-generated
- Values
- ID reference to header button
- Required
- Yes (if region used)
WAI-ARIA States
aria-expanded
- Target Element
- button element
- Values
- true | false
- Required
- Yes
- Change Trigger
- Click, Enter, Space
aria-disabled
- Target Element
- button element
- Values
- true | false
- Required
- No
- Change Trigger
- Only when disabled
Keyboard Support
| Key | Action |
|---|---|
| Tab | Move focus to the next focusable element |
| Shift + Tab | Move focus to the previous focusable element |
| Space / Enter | Toggle the expansion of the focused accordion header |
- Header navigation uses the standard Tab order; arrow / Home / End key navigation is no longer part of the APG Accordion keyboard interaction.
Focus Management
| Event | Behavior |
|---|---|
| Header buttons | Focusable via their button elements |
| Tab order | Headers participate in the page Tab sequence; navigate between headers with Tab / Shift+Tab |
Implementation Notes
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ [โผ] Section 1 โ โ button (aria-expanded="true")
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค
โ Panel 1 content... โ โ region (aria-labelledby)
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค
โ [โถ] Section 2 โ โ button (aria-expanded="false")
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค
โ [โถ] Section 3 โ โ button (aria-expanded="false")
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
ID Relationships:
- Button: id="header-1", aria-controls="panel-1"
- Panel: id="panel-1", aria-labelledby="header-1"
Region Role Rule:
- โค6 panels: use role="region" on panels
- >6 panels: omit role="region" (too many landmarks)
Accordion component structure with ID relationships
References
Source Code
<template>
<div :class="`apg-accordion ${className}`.trim()">
<div v-for="item in items" :key="item.id" :class="getItemClass(item)">
<component :is="`h${headingLevel}`" class="apg-accordion-header">
<button
type="button"
:id="`${instanceId}-header-${item.id}`"
:aria-expanded="isExpanded(item.id)"
:aria-controls="`${instanceId}-panel-${item.id}`"
:aria-disabled="item.disabled || undefined"
:disabled="item.disabled"
:class="getTriggerClass(item)"
@click="handleToggle(item.id)"
>
<span class="apg-accordion-trigger-content">{{ item.header }}</span>
<span :class="getIconClass(item)" aria-hidden="true">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<polyline points="6 9 12 15 18 9" />
</svg>
</span>
</button>
</component>
<div
:role="useRegion ? 'region' : undefined"
:id="`${instanceId}-panel-${item.id}`"
:aria-labelledby="useRegion ? `${instanceId}-header-${item.id}` : undefined"
:class="getPanelClass(item)"
>
<div class="apg-accordion-panel-content">
<div v-if="item.content" v-html="item.content" />
<slot v-else :name="item.id" />
</div>
</div>
</div>
</div>
</template>
<script setup lang="ts">
/**
* APG Accordion Pattern - Vue Implementation
*
* A vertically stacked set of interactive headings that each reveal a section of content.
*
* @see https://www.w3.org/WAI/ARIA/apg/patterns/accordion/
*/
import { ref, computed } from 'vue';
/**
* Accordion item configuration
*/
export interface AccordionItem {
/** Unique identifier for the item */
id: string;
/** Content displayed in the accordion header button */
header: string;
/** Content displayed in the collapsible panel (HTML string) */
content?: string;
/** When true, the item cannot be expanded/collapsed */
disabled?: boolean;
/** When true, the panel is expanded on initial render */
defaultExpanded?: boolean;
}
/**
* Props for the Accordion component
*
* @example
* ```vue
* <Accordion
* :items="[
* { id: 'section1', header: 'Section 1', content: 'Content 1', defaultExpanded: true },
* { id: 'section2', header: 'Section 2', content: 'Content 2' },
* ]"
* :heading-level="3"
* :allow-multiple="false"
* @expanded-change="(ids) => console.log('Expanded:', ids)"
* />
* ```
*/
export interface AccordionProps {
/** Array of accordion items to display */
items: AccordionItem[];
/** Allow multiple panels to be expanded simultaneously @default false */
allowMultiple?: boolean;
/** Heading level for accessibility (h2-h6) @default 3 */
headingLevel?: 2 | 3 | 4 | 5 | 6;
/** Additional CSS class @default "" */
className?: string;
}
const props = withDefaults(defineProps<AccordionProps>(), {
allowMultiple: false,
headingLevel: 3,
className: '',
});
const emit = defineEmits<{
expandedChange: [expandedIds: string[]];
}>();
// Initialize with defaultExpanded items immediately
const getInitialExpandedIds = () => {
return props.items
.filter((item) => item.defaultExpanded && !item.disabled)
.map((item) => item.id);
};
const expandedIds = ref<string[]>(getInitialExpandedIds());
const instanceId = ref(`accordion-${Math.random().toString(36).substr(2, 9)}`);
// Use role="region" only for 6 or fewer panels (APG recommendation)
const useRegion = computed(() => props.items.length <= 6);
const isExpanded = (itemId: string) => expandedIds.value.includes(itemId);
const getItemClass = (item: AccordionItem) => {
const classes = ['apg-accordion-item'];
if (isExpanded(item.id)) classes.push('apg-accordion-item--expanded');
if (item.disabled) classes.push('apg-accordion-item--disabled');
return classes.join(' ');
};
const getTriggerClass = (item: AccordionItem) => {
const classes = ['apg-accordion-trigger'];
if (isExpanded(item.id)) classes.push('apg-accordion-trigger--expanded');
return classes.join(' ');
};
const getIconClass = (item: AccordionItem) => {
const classes = ['apg-accordion-icon'];
if (isExpanded(item.id)) classes.push('apg-accordion-icon--expanded');
return classes.join(' ');
};
const getPanelClass = (item: AccordionItem) => {
return `apg-accordion-panel ${isExpanded(item.id) ? 'apg-accordion-panel--expanded' : 'apg-accordion-panel--collapsed'}`;
};
const handleToggle = (itemId: string) => {
const item = props.items.find((i) => i.id === itemId);
if (item?.disabled) return;
const isCurrentlyExpanded = expandedIds.value.includes(itemId);
if (isCurrentlyExpanded) {
expandedIds.value = expandedIds.value.filter((id) => id !== itemId);
} else {
if (props.allowMultiple) {
expandedIds.value = [...expandedIds.value, itemId];
} else {
expandedIds.value = [itemId];
}
}
emit('expandedChange', expandedIds.value);
};
</script> Usage
<script setup>
import Accordion from './Accordion.vue';
const items = [
{
id: 'section1',
header: 'First Section',
content: 'Content for the first section...',
defaultExpanded: true,
},
{
id: 'section2',
header: 'Second Section',
content: 'Content for the second section...',
},
];
</script>
<template>
<Accordion
:items="items"
:heading-level="3"
:allow-multiple="false"
@expanded-change="(ids) => console.log('Expanded:', ids)"
/>
</template> API
| Prop | Type | Default | Description |
|---|---|---|---|
items | AccordionItem[] | required | Array of accordion items |
allowMultiple | boolean | false | Allow multiple panels to be expanded |
headingLevel | 2 | 3 | 4 | 5 | 6 | 3 | Heading level for accessibility |
AccordionItem Props
| Prop | Type | Default | Description |
|---|---|---|---|
id | string | required | Unique item identifier |
header | string | required | Header text for the accordion trigger |
content | string | required | Content of the accordion panel |
disabled | boolean | false | Whether the item is disabled |
defaultExpanded | boolean | false | Whether the item is initially expanded |
Custom Events
| Event | Detail | Description |
|---|---|---|
expanded-change | string[] | Emitted when the expanded panels change |
Testing
Tests verify APG compliance across keyboard interaction, ARIA attributes, and accessibility requirements. The Accordion component uses a two-layer testing strategy.
Testing Strategy
Unit Tests (Testing Library)
Verify the component's rendered output using framework-specific testing libraries. These tests ensure correct HTML structure and ARIA attributes.
- ARIA attributes (aria-expanded, aria-controls, aria-labelledby)
- Keyboard interaction (Enter, Space)
- Expand/collapse behavior
- Accessibility via jest-axe
E2E Tests (Playwright)
Verify component behavior in a real browser environment across all frameworks. These tests cover interactions and cross-framework consistency.
- Click interactions
- Enter / Space toggle
- ARIA structure validation in live browser
- axe-core accessibility scanning
- Cross-framework consistency checks
Test Categories
High Priority : APG Keyboard Interaction (Unit + E2E)
| Test | Description |
|---|---|
Enter key | Expands/collapses the focused panel |
Space key | Expands/collapses the focused panel |
High Priority : APG ARIA Attributes (Unit + E2E)
| Test | Description |
|---|---|
aria-expanded | Header button reflects expand/collapse state |
aria-controls | Header references its panel via aria-controls |
aria-labelledby | Panel references its header via aria-labelledby |
role="region" | Panel has region role (6 or fewer panels) |
No region (7+) | Panel omits region role when 7+ panels |
aria-disabled | Disabled items have aria-disabled="true" |
High Priority : Click Interaction (Unit + E2E)
| Test | Description |
|---|---|
Click expands | Clicking header expands panel |
Click collapses | Clicking expanded header collapses panel |
Single expansion | Opening panel closes other panels (default) |
Multiple expansion | Multiple panels can be open with allowMultiple |
High Priority : Heading Structure (Unit + E2E)
| Test | Description |
|---|---|
headingLevel prop | Uses correct heading element (h2, h3, etc.) |
Medium Priority : Disabled State (Unit + E2E)
| Test | Description |
|---|---|
Disabled no click | Clicking disabled header does not expand |
Disabled no keyboard | Enter/Space does not activate disabled header |
Medium Priority : Accessibility (Unit + E2E)
| Test | Description |
|---|---|
axe violations | No WCAG 2.1 AA violations (via jest-axe/axe-core) |
Low Priority : Cross-framework Consistency (E2E)
| Test | Description |
|---|---|
All frameworks render | React, Vue, Svelte, Astro all render accordions |
Consistent ARIA | All frameworks have consistent ARIA structure |
Example Test Code
The following is the actual E2E test file (e2e/accordion.spec.ts).
import { test, expect } from '@playwright/test';
import AxeBuilder from '@axe-core/playwright';
/**
* E2E Tests for Accordion Pattern
*
* A vertically stacked set of interactive headings that each reveal
* a section of content.
*
* APG Reference: https://www.w3.org/WAI/ARIA/apg/patterns/accordion/
*/
const frameworks = ['react', 'vue', 'svelte', 'astro'] as const;
// ============================================
// Helper Functions
// ============================================
const getAccordion = (page: import('@playwright/test').Page) => {
return page.locator('.apg-accordion');
};
const getAccordionHeaders = (page: import('@playwright/test').Page) => {
return page.locator('.apg-accordion-trigger');
};
// ============================================
// Framework-specific Tests
// ============================================
for (const framework of frameworks) {
test.describe(`Accordion (${framework})`, () => {
test.beforeEach(async ({ page }) => {
await page.goto(`patterns/accordion/${framework}/demo/`);
await getAccordion(page).first().waitFor();
// Wait for hydration to complete - aria-controls should have a proper ID (not starting with hyphen)
const firstHeader = getAccordionHeaders(page).first();
await expect
.poll(async () => {
const id = await firstHeader.getAttribute('aria-controls');
// ID should be non-empty and not start with hyphen (Svelte pre-hydration)
return id && id.length > 1 && !id.startsWith('-');
})
.toBe(true);
});
// ------------------------------------------
// ๐ด High Priority: APG ARIA Structure
// ------------------------------------------
test.describe('APG: ARIA Structure', () => {
test('accordion headers have aria-expanded attribute', async ({ page }) => {
const headers = getAccordionHeaders(page);
const firstHeader = headers.first();
// Should have aria-expanded (either true or false)
const expanded = await firstHeader.getAttribute('aria-expanded');
expect(['true', 'false']).toContain(expanded);
});
test('accordion headers have aria-controls referencing panel', async ({ page }) => {
const headers = getAccordionHeaders(page);
const firstHeader = headers.first();
// Wait for aria-controls to be set
await expect(firstHeader).toHaveAttribute('aria-controls', /.+/);
const controlsId = await firstHeader.getAttribute('aria-controls');
expect(controlsId).toBeTruthy();
// Panel with that ID should exist
const panel = page.locator(`[id="${controlsId}"]`);
await expect(panel).toBeAttached();
});
test('panels have role="region" when 6 or fewer items', async ({ page }) => {
const accordion = getAccordion(page).first();
const headers = accordion.locator('.apg-accordion-trigger');
const count = await headers.count();
if (count <= 6) {
const panels = accordion.locator('.apg-accordion-panel');
const firstPanel = panels.first();
await expect(firstPanel).toHaveRole('region');
}
});
test('panels have aria-labelledby referencing header', async ({ page }) => {
const accordion = getAccordion(page).first();
const headers = accordion.locator('.apg-accordion-trigger');
const count = await headers.count();
// Only check aria-labelledby when role="region" is present (โค6 items)
if (count <= 6) {
const firstHeader = headers.first();
// Wait for aria-controls to be set
await expect(firstHeader).toHaveAttribute('aria-controls', /.+/);
const headerId = await firstHeader.getAttribute('id');
const controlsId = await firstHeader.getAttribute('aria-controls');
const panel = page.locator(`[id="${controlsId}"]`);
await expect(panel).toHaveAttribute('aria-labelledby', headerId!);
}
});
});
// ------------------------------------------
// ๐ด High Priority: Click Interaction
// ------------------------------------------
test.describe('APG: Click Interaction', () => {
test('clicking header toggles panel expansion', async ({ page }) => {
const accordion = getAccordion(page).first();
// Use second header which is not expanded by default
const header = accordion.locator('.apg-accordion-trigger').nth(1);
// Wait for component to be interactive (hydration complete)
await expect(header).toHaveAttribute('aria-expanded', 'false');
await header.click();
await expect(header).toHaveAttribute('aria-expanded', 'true');
});
test('single expansion mode: opening one panel closes others', async ({ page }) => {
// First accordion uses single expansion mode
const accordion = getAccordion(page).first();
const headers = accordion.locator('.apg-accordion-trigger');
// Wait for hydration - first header should be expanded by default
const firstHeader = headers.first();
await expect(firstHeader).toHaveAttribute('aria-expanded', 'true');
// Click second header
const secondHeader = headers.nth(1);
await secondHeader.click();
// Second should be open, first should be closed
await expect(secondHeader).toHaveAttribute('aria-expanded', 'true');
await expect(firstHeader).toHaveAttribute('aria-expanded', 'false');
});
});
// ------------------------------------------
// ๐ด High Priority: Keyboard Interaction
// ------------------------------------------
test.describe('APG: Keyboard Interaction', () => {
test('Enter/Space toggles panel expansion', async ({ page }) => {
const accordion = getAccordion(page).first();
// Use second header which is collapsed by default
const header = accordion.locator('.apg-accordion-trigger').nth(1);
// Wait for component to be ready
await expect(header).toHaveAttribute('aria-expanded', 'false');
// Click to set focus (this also opens the panel)
await header.click();
await expect(header).toBeFocused();
await expect(header).toHaveAttribute('aria-expanded', 'true');
// Press Enter to toggle (should collapse)
await expect(header).toBeFocused();
await header.press('Enter');
await expect(header).toHaveAttribute('aria-expanded', 'false');
// Press Space to toggle (should expand)
await expect(header).toBeFocused();
await header.press('Space');
await expect(header).toHaveAttribute('aria-expanded', 'true');
});
});
// ------------------------------------------
// ๐ก Medium Priority: Disabled State
// ------------------------------------------
test.describe('Disabled State', () => {
test('disabled header cannot be clicked to expand', async ({ page }) => {
// Third accordion has disabled items
const accordions = getAccordion(page);
const count = await accordions.count();
// Find accordion with disabled item
for (let i = 0; i < count; i++) {
const accordion = accordions.nth(i);
const disabledHeader = accordion.locator('.apg-accordion-trigger[disabled]');
if ((await disabledHeader.count()) > 0) {
const header = disabledHeader.first();
const initialExpanded = await header.getAttribute('aria-expanded');
await header.click({ force: true });
// State should not change
await expect(header).toHaveAttribute('aria-expanded', initialExpanded!);
break;
}
}
});
});
// ------------------------------------------
// ๐ข Low Priority: Accessibility
// ------------------------------------------
test.describe('Accessibility', () => {
test('has no axe-core violations', async ({ page }) => {
const accordion = getAccordion(page);
await accordion.first().waitFor();
const results = await new AxeBuilder({ page })
.include('.apg-accordion')
.disableRules(['color-contrast'])
.analyze();
expect(results.violations).toEqual([]);
});
});
});
}
// ============================================
// Cross-framework Consistency Tests
// ============================================
test.describe('Accordion - Cross-framework Consistency', () => {
test('all frameworks have accordions', async ({ page }) => {
for (const framework of frameworks) {
await page.goto(`patterns/accordion/${framework}/demo/`);
await getAccordion(page).first().waitFor();
const accordions = getAccordion(page);
const count = await accordions.count();
expect(count).toBeGreaterThan(0);
}
});
test('all frameworks support click to expand', async ({ page }) => {
for (const framework of frameworks) {
await page.goto(`patterns/accordion/${framework}/demo/`);
await getAccordion(page).first().waitFor();
const accordion = getAccordion(page).first();
// Use second header which is not expanded by default
const header = accordion.locator('.apg-accordion-trigger').nth(1);
// Wait for the component to be interactive (not expanded by default)
await expect(header).toHaveAttribute('aria-expanded', 'false');
// Click to toggle
await header.click();
// State should change to expanded
await expect(header).toHaveAttribute('aria-expanded', 'true');
}
});
test('all frameworks have consistent ARIA structure', async ({ page }) => {
for (const framework of frameworks) {
await page.goto(`patterns/accordion/${framework}/demo/`);
await getAccordion(page).first().waitFor();
const accordion = getAccordion(page).first();
const header = accordion.locator('.apg-accordion-trigger').first();
// Wait for hydration - aria-controls should be set
await expect(header).toHaveAttribute('aria-controls', /.+/);
// Check aria-expanded exists
const expanded = await header.getAttribute('aria-expanded');
expect(['true', 'false']).toContain(expanded);
// Check aria-controls exists and references valid panel
const controlsId = await header.getAttribute('aria-controls');
expect(controlsId).toBeTruthy();
const panel = page.locator(`[id="${controlsId}"]`);
await expect(panel).toBeAttached();
}
});
}); Running Tests
# Run unit tests for Accordion
npm run test -- accordion
# Run E2E tests for Accordion (all frameworks)
npm run test:e2e:pattern --pattern=accordion
# Run E2E tests for specific framework
npm run test:e2e:react:pattern --pattern=accordion
npm run test:e2e:vue:pattern --pattern=accordion
npm run test:e2e:svelte:pattern --pattern=accordion
npm run test:e2e:astro:pattern --pattern=accordion
Testing Tools
- Vitest (opens in new tab) - Test runner for unit tests
- Testing Library (opens in new tab) - Framework-specific testing utilities (React, Vue, Svelte)
- Playwright (opens in new tab) - Browser automation for E2E tests
- axe-core/playwright (opens in new tab) - Automated accessibility testing in E2E
See the Testing Strategy guide for details.
import { render, screen } from '@testing-library/vue';
import userEvent from '@testing-library/user-event';
import { axe } from 'jest-axe';
import { describe, expect, it, vi } from 'vitest';
import Accordion from './Accordion.vue';
import type { AccordionItem } from './Accordion.vue';
// ใในใ็จใฎใขใณใผใใฃใชใณใใผใฟ
const defaultItems: AccordionItem[] = [
{ id: 'section1', header: 'Section 1', content: 'Content 1' },
{ id: 'section2', header: 'Section 2', content: 'Content 2' },
{ id: 'section3', header: 'Section 3', content: 'Content 3' },
];
const itemsWithDisabled: AccordionItem[] = [
{ id: 'section1', header: 'Section 1', content: 'Content 1' },
{ id: 'section2', header: 'Section 2', content: 'Content 2', disabled: true },
{ id: 'section3', header: 'Section 3', content: 'Content 3' },
];
const itemsWithDefaultExpanded: AccordionItem[] = [
{ id: 'section1', header: 'Section 1', content: 'Content 1', defaultExpanded: true },
{ id: 'section2', header: 'Section 2', content: 'Content 2' },
{ id: 'section3', header: 'Section 3', content: 'Content 3' },
];
// 7ๅไปฅไธใฎใขใคใใ ๏ผregion role ใในใ็จ๏ผ
const manyItems: AccordionItem[] = Array.from({ length: 7 }, (_, i) => ({
id: `section${i + 1}`,
header: `Section ${i + 1}`,
content: `Content ${i + 1}`,
}));
describe('Accordion (Vue)', () => {
// ๐ด High Priority: APG ๆบๆ ใฎๆ ธๅฟ
describe('APG: ใญใผใใผใๆไฝ', () => {
it('Enter ใงใใใซใ้้ใใ', async () => {
const user = userEvent.setup();
render(Accordion, { props: { items: defaultItems } });
const button = screen.getByRole('button', { name: 'Section 1' });
button.focus();
expect(button).toHaveAttribute('aria-expanded', 'false');
await user.keyboard('{Enter}');
expect(button).toHaveAttribute('aria-expanded', 'true');
await user.keyboard('{Enter}');
expect(button).toHaveAttribute('aria-expanded', 'false');
});
it('Space ใงใใใซใ้้ใใ', async () => {
const user = userEvent.setup();
render(Accordion, { props: { items: defaultItems } });
const button = screen.getByRole('button', { name: 'Section 1' });
button.focus();
expect(button).toHaveAttribute('aria-expanded', 'false');
await user.keyboard(' ');
expect(button).toHaveAttribute('aria-expanded', 'true');
});
});
describe('APG: ARIA ๅฑๆง', () => {
it('ใใใใผใใฟใณใ aria-expanded ใๆใค', () => {
render(Accordion, { props: { items: defaultItems } });
const buttons = screen.getAllByRole('button');
buttons.forEach((button) => {
expect(button).toHaveAttribute('aria-expanded');
});
});
it('้ใใใใใซใง aria-expanded="true"', async () => {
const user = userEvent.setup();
render(Accordion, { props: { items: defaultItems } });
const button = screen.getByRole('button', { name: 'Section 1' });
await user.click(button);
expect(button).toHaveAttribute('aria-expanded', 'true');
});
it('้ใใใใใซใง aria-expanded="false"', () => {
render(Accordion, { props: { items: defaultItems } });
const button = screen.getByRole('button', { name: 'Section 1' });
expect(button).toHaveAttribute('aria-expanded', 'false');
});
it('ใใใใผใฎ aria-controls ใใใใซ id ใจไธ่ด', () => {
render(Accordion, { props: { items: defaultItems } });
const button = screen.getByRole('button', { name: 'Section 1' });
const ariaControls = button.getAttribute('aria-controls');
expect(ariaControls).toBeTruthy();
expect(document.getElementById(ariaControls!)).toBeInTheDocument();
});
it('6ๅไปฅไธใฎใใใซใง role="region" ใๆใค', () => {
render(Accordion, { props: { items: defaultItems } });
const regions = screen.getAllByRole('region');
expect(regions).toHaveLength(3);
});
it('7ๅไปฅไธใฎใใใซใง role="region" ใๆใใชใ', () => {
render(Accordion, { props: { items: manyItems } });
const regions = screen.queryAllByRole('region');
expect(regions).toHaveLength(0);
});
it('ใใใซใฎ aria-labelledby ใใใใใผ id ใจไธ่ด', () => {
render(Accordion, { props: { items: defaultItems } });
const button = screen.getByRole('button', { name: 'Section 1' });
const regions = screen.getAllByRole('region');
expect(regions[0]).toHaveAttribute('aria-labelledby', button.id);
});
it('disabled ้
็ฎใ aria-disabled="true" ใๆใค', () => {
render(Accordion, { props: { items: itemsWithDisabled } });
const disabledButton = screen.getByRole('button', { name: 'Section 2' });
expect(disabledButton).toHaveAttribute('aria-disabled', 'true');
});
});
describe('APG: ่ฆๅบใๆง้ ', () => {
it('headingLevel=3 ใง h3 ่ฆ็ด ใไฝฟ็จ', () => {
render(Accordion, { props: { items: defaultItems, headingLevel: 3 } });
const headings = document.querySelectorAll('h3');
expect(headings).toHaveLength(3);
});
it('headingLevel=2 ใง h2 ่ฆ็ด ใไฝฟ็จ', () => {
render(Accordion, { props: { items: defaultItems, headingLevel: 2 } });
const headings = document.querySelectorAll('h2');
expect(headings).toHaveLength(3);
});
});
// ๐ก Medium Priority: ใขใฏใปใทใใชใใฃๆค่จผ
describe('ใขใฏใปใทใใชใใฃ', () => {
it('axe ใซใใ WCAG 2.1 AA ้ๅใใชใ', async () => {
const { container } = render(Accordion, { props: { items: defaultItems } });
const results = await axe(container);
expect(results).toHaveNoViolations();
});
});
describe('Props', () => {
it('defaultExpanded ใงๅๆๅฑ้็ถๆ
ใๆๅฎใงใใ', () => {
render(Accordion, { props: { items: itemsWithDefaultExpanded } });
const button = screen.getByRole('button', { name: 'Section 1' });
expect(button).toHaveAttribute('aria-expanded', 'true');
});
it('allowMultiple=false ใง1ใคใฎใฟๅฑ้๏ผใใใฉใซใ๏ผ', async () => {
const user = userEvent.setup();
render(Accordion, { props: { items: defaultItems } });
const button1 = screen.getByRole('button', { name: 'Section 1' });
const button2 = screen.getByRole('button', { name: 'Section 2' });
await user.click(button1);
expect(button1).toHaveAttribute('aria-expanded', 'true');
await user.click(button2);
expect(button1).toHaveAttribute('aria-expanded', 'false');
expect(button2).toHaveAttribute('aria-expanded', 'true');
});
it('allowMultiple=true ใง่คๆฐๅฑ้ๅฏ่ฝ', async () => {
const user = userEvent.setup();
render(Accordion, { props: { items: defaultItems, allowMultiple: true } });
const button1 = screen.getByRole('button', { name: 'Section 1' });
const button2 = screen.getByRole('button', { name: 'Section 2' });
await user.click(button1);
await user.click(button2);
expect(button1).toHaveAttribute('aria-expanded', 'true');
expect(button2).toHaveAttribute('aria-expanded', 'true');
});
it('@expandedChange ใๅฑ้็ถๆ
ๅคๅๆใซ็บ็ซใใ', async () => {
const handleExpandedChange = vi.fn();
const user = userEvent.setup();
render(Accordion, {
props: { items: defaultItems, onExpandedChange: handleExpandedChange },
});
await user.click(screen.getByRole('button', { name: 'Section 1' }));
expect(handleExpandedChange).toHaveBeenCalledWith(['section1']);
});
});
describe('็ฐๅธธ็ณป', () => {
it('disabled ้
็ฎใฏใฏใชใใฏใง้้ใใชใ', async () => {
const user = userEvent.setup();
render(Accordion, { props: { items: itemsWithDisabled } });
const disabledButton = screen.getByRole('button', { name: 'Section 2' });
expect(disabledButton).toHaveAttribute('aria-expanded', 'false');
await user.click(disabledButton);
expect(disabledButton).toHaveAttribute('aria-expanded', 'false');
});
it('disabled ใใค defaultExpanded ใฎ้
็ฎใฏๅฑ้ใใใชใ', () => {
const items: AccordionItem[] = [
{
id: 'section1',
header: 'Section 1',
content: 'Content 1',
disabled: true,
defaultExpanded: true,
},
];
render(Accordion, { props: { items } });
const button = screen.getByRole('button', { name: 'Section 1' });
expect(button).toHaveAttribute('aria-expanded', 'false');
});
});
}); Resources
- WAI-ARIA APG: Accordion Pattern (opens in new tab)
- AI Implementation Guide (llm.md) (opens in new tab) - ARIA specs, keyboard support, test checklist