Files
e-ticket/tests/js/tabs.test.js

255 lines
9.8 KiB
JavaScript
Raw Permalink Normal View History

import { describe, it, expect, beforeEach } from 'vitest'
import { initTabs } from '../../assets/modules/tabs.js'
Complete TASK_CHECKUP: security, UX, tests, coverage, accessibility, config externalization Billetterie: - Partial refund support (STATUS_PARTIALLY_REFUNDED, refundedAmount field, migration) - Race condition fix: PESSIMISTIC_WRITE lock on stock decrement in transaction - Idempotency key on PaymentIntent::create, reuse existing PI if stripeSessionId set - Disable checkout when event ended (server 400 + template hide) - Webhook deduplication via cache (24h TTL on stripe event.id) - Email validation (filter_var) in OrderController guest flow - JSON cart validation (structure check before processing) - Invitation expiration after 7 days (isExpired method + landing page message) - Stripe Checkout fallback when JS fails to load (noscript + redirect) Config externalization: - Move Stripe fees (STRIPE_FEE_RATE, STRIPE_FEE_FIXED) and admin email (ADMIN_EMAIL) to .env/services.yaml - Replace all hardcoded contact@e-cosplay.fr across 13 files - MailerService: getAdminEmail()/getAdminFrom(), default $from=null resolves to admin UX & Accessibility: - ARIA tabs: role=tablist/tab/tabpanel, aria-selected, keyboard nav (arrows, Home, End) - aria-label on cart +/- buttons and editor toolbar buttons - tabindex=0 on editor toolbar buttons for keyboard access - data-confirm handler in app.js (was only in admin.js) - Cart error feedback on checkout failure - Billet designer save feedback (loading/success/error states) - Stock polling every 30s with rupture/low stock badges - Back to event link on payment page Security: - HTML sanitizer: BLOCKED_TAGS list (script, style, iframe, svg, etc.) - content fully removed - Stripe polling timeout (15s max) with fallback redirect - Rate limiting on public order access (20/5min) - .catch() on all fetch() calls (sortable, billet-designer) Tests (92% PHP, 100% JS lines): - PCOV added to dev Dockerfile - Test DB setup: .env.test with DATABASE_URL, Redis auth, Meilisearch key - Rate limiter disabled in test env - Makefile: test_db_setup, test_db_reset, run_test_php, run_test_coverage_php/js - New tests: InvitationFlowTest (21), AuditServiceTest (4), ExportServiceTest (9), InvoiceServiceTest (4) - New tests: SuspendedUserSubscriberTest, RateLimiterSubscriberTest, MeilisearchServiceTest - New tests: Stripe webhook payment_failed (6) + charge.refunded (6) - New tests: BilletBuyer refund, User suspended, OrganizerInvitation expiration - JS tests: stock polling (6), data-confirm (2), copy-url restore (1), editor ARIA (2), XSS (9), tabs keyboard (9) - ESLint + PHP CS Fixer: 0 errors - SonarQube exclusions aligned with vitest coverage config Infra: - Meilisearch consistency command (app:meilisearch:check-consistency --fix) + cron daily 3am - MeilisearchService: getAllDocumentIds(), listIndexes() Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-23 11:14:06 +01:00
function setup() {
document.body.innerHTML = `
<div id="tablist">
<button data-tab="tab-a" style="background-color:#111827;color:white;">Tab A</button>
<button data-tab="tab-b" style="background-color:white;color:#111827;">Tab B</button>
Complete TASK_CHECKUP: security, UX, tests, coverage, accessibility, config externalization Billetterie: - Partial refund support (STATUS_PARTIALLY_REFUNDED, refundedAmount field, migration) - Race condition fix: PESSIMISTIC_WRITE lock on stock decrement in transaction - Idempotency key on PaymentIntent::create, reuse existing PI if stripeSessionId set - Disable checkout when event ended (server 400 + template hide) - Webhook deduplication via cache (24h TTL on stripe event.id) - Email validation (filter_var) in OrderController guest flow - JSON cart validation (structure check before processing) - Invitation expiration after 7 days (isExpired method + landing page message) - Stripe Checkout fallback when JS fails to load (noscript + redirect) Config externalization: - Move Stripe fees (STRIPE_FEE_RATE, STRIPE_FEE_FIXED) and admin email (ADMIN_EMAIL) to .env/services.yaml - Replace all hardcoded contact@e-cosplay.fr across 13 files - MailerService: getAdminEmail()/getAdminFrom(), default $from=null resolves to admin UX & Accessibility: - ARIA tabs: role=tablist/tab/tabpanel, aria-selected, keyboard nav (arrows, Home, End) - aria-label on cart +/- buttons and editor toolbar buttons - tabindex=0 on editor toolbar buttons for keyboard access - data-confirm handler in app.js (was only in admin.js) - Cart error feedback on checkout failure - Billet designer save feedback (loading/success/error states) - Stock polling every 30s with rupture/low stock badges - Back to event link on payment page Security: - HTML sanitizer: BLOCKED_TAGS list (script, style, iframe, svg, etc.) - content fully removed - Stripe polling timeout (15s max) with fallback redirect - Rate limiting on public order access (20/5min) - .catch() on all fetch() calls (sortable, billet-designer) Tests (92% PHP, 100% JS lines): - PCOV added to dev Dockerfile - Test DB setup: .env.test with DATABASE_URL, Redis auth, Meilisearch key - Rate limiter disabled in test env - Makefile: test_db_setup, test_db_reset, run_test_php, run_test_coverage_php/js - New tests: InvitationFlowTest (21), AuditServiceTest (4), ExportServiceTest (9), InvoiceServiceTest (4) - New tests: SuspendedUserSubscriberTest, RateLimiterSubscriberTest, MeilisearchServiceTest - New tests: Stripe webhook payment_failed (6) + charge.refunded (6) - New tests: BilletBuyer refund, User suspended, OrganizerInvitation expiration - JS tests: stock polling (6), data-confirm (2), copy-url restore (1), editor ARIA (2), XSS (9), tabs keyboard (9) - ESLint + PHP CS Fixer: 0 errors - SonarQube exclusions aligned with vitest coverage config Infra: - Meilisearch consistency command (app:meilisearch:check-consistency --fix) + cron daily 3am - MeilisearchService: getAllDocumentIds(), listIndexes() Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-23 11:14:06 +01:00
<button data-tab="tab-c" style="background-color:white;color:#111827;">Tab C</button>
</div>
<div id="tab-a" style="display:block;">Content A</div>
<div id="tab-b" style="display:none;">Content B</div>
<div id="tab-c" style="display:none;">Content C</div>
`
initTabs()
}
Complete TASK_CHECKUP: security, UX, tests, coverage, accessibility, config externalization Billetterie: - Partial refund support (STATUS_PARTIALLY_REFUNDED, refundedAmount field, migration) - Race condition fix: PESSIMISTIC_WRITE lock on stock decrement in transaction - Idempotency key on PaymentIntent::create, reuse existing PI if stripeSessionId set - Disable checkout when event ended (server 400 + template hide) - Webhook deduplication via cache (24h TTL on stripe event.id) - Email validation (filter_var) in OrderController guest flow - JSON cart validation (structure check before processing) - Invitation expiration after 7 days (isExpired method + landing page message) - Stripe Checkout fallback when JS fails to load (noscript + redirect) Config externalization: - Move Stripe fees (STRIPE_FEE_RATE, STRIPE_FEE_FIXED) and admin email (ADMIN_EMAIL) to .env/services.yaml - Replace all hardcoded contact@e-cosplay.fr across 13 files - MailerService: getAdminEmail()/getAdminFrom(), default $from=null resolves to admin UX & Accessibility: - ARIA tabs: role=tablist/tab/tabpanel, aria-selected, keyboard nav (arrows, Home, End) - aria-label on cart +/- buttons and editor toolbar buttons - tabindex=0 on editor toolbar buttons for keyboard access - data-confirm handler in app.js (was only in admin.js) - Cart error feedback on checkout failure - Billet designer save feedback (loading/success/error states) - Stock polling every 30s with rupture/low stock badges - Back to event link on payment page Security: - HTML sanitizer: BLOCKED_TAGS list (script, style, iframe, svg, etc.) - content fully removed - Stripe polling timeout (15s max) with fallback redirect - Rate limiting on public order access (20/5min) - .catch() on all fetch() calls (sortable, billet-designer) Tests (92% PHP, 100% JS lines): - PCOV added to dev Dockerfile - Test DB setup: .env.test with DATABASE_URL, Redis auth, Meilisearch key - Rate limiter disabled in test env - Makefile: test_db_setup, test_db_reset, run_test_php, run_test_coverage_php/js - New tests: InvitationFlowTest (21), AuditServiceTest (4), ExportServiceTest (9), InvoiceServiceTest (4) - New tests: SuspendedUserSubscriberTest, RateLimiterSubscriberTest, MeilisearchServiceTest - New tests: Stripe webhook payment_failed (6) + charge.refunded (6) - New tests: BilletBuyer refund, User suspended, OrganizerInvitation expiration - JS tests: stock polling (6), data-confirm (2), copy-url restore (1), editor ARIA (2), XSS (9), tabs keyboard (9) - ESLint + PHP CS Fixer: 0 errors - SonarQube exclusions aligned with vitest coverage config Infra: - Meilisearch consistency command (app:meilisearch:check-consistency --fix) + cron daily 3am - MeilisearchService: getAllDocumentIds(), listIndexes() Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-23 11:14:06 +01:00
describe('initTabs', () => {
beforeEach(() => setup())
Complete TASK_CHECKUP: security, UX, tests, coverage, accessibility, config externalization Billetterie: - Partial refund support (STATUS_PARTIALLY_REFUNDED, refundedAmount field, migration) - Race condition fix: PESSIMISTIC_WRITE lock on stock decrement in transaction - Idempotency key on PaymentIntent::create, reuse existing PI if stripeSessionId set - Disable checkout when event ended (server 400 + template hide) - Webhook deduplication via cache (24h TTL on stripe event.id) - Email validation (filter_var) in OrderController guest flow - JSON cart validation (structure check before processing) - Invitation expiration after 7 days (isExpired method + landing page message) - Stripe Checkout fallback when JS fails to load (noscript + redirect) Config externalization: - Move Stripe fees (STRIPE_FEE_RATE, STRIPE_FEE_FIXED) and admin email (ADMIN_EMAIL) to .env/services.yaml - Replace all hardcoded contact@e-cosplay.fr across 13 files - MailerService: getAdminEmail()/getAdminFrom(), default $from=null resolves to admin UX & Accessibility: - ARIA tabs: role=tablist/tab/tabpanel, aria-selected, keyboard nav (arrows, Home, End) - aria-label on cart +/- buttons and editor toolbar buttons - tabindex=0 on editor toolbar buttons for keyboard access - data-confirm handler in app.js (was only in admin.js) - Cart error feedback on checkout failure - Billet designer save feedback (loading/success/error states) - Stock polling every 30s with rupture/low stock badges - Back to event link on payment page Security: - HTML sanitizer: BLOCKED_TAGS list (script, style, iframe, svg, etc.) - content fully removed - Stripe polling timeout (15s max) with fallback redirect - Rate limiting on public order access (20/5min) - .catch() on all fetch() calls (sortable, billet-designer) Tests (92% PHP, 100% JS lines): - PCOV added to dev Dockerfile - Test DB setup: .env.test with DATABASE_URL, Redis auth, Meilisearch key - Rate limiter disabled in test env - Makefile: test_db_setup, test_db_reset, run_test_php, run_test_coverage_php/js - New tests: InvitationFlowTest (21), AuditServiceTest (4), ExportServiceTest (9), InvoiceServiceTest (4) - New tests: SuspendedUserSubscriberTest, RateLimiterSubscriberTest, MeilisearchServiceTest - New tests: Stripe webhook payment_failed (6) + charge.refunded (6) - New tests: BilletBuyer refund, User suspended, OrganizerInvitation expiration - JS tests: stock polling (6), data-confirm (2), copy-url restore (1), editor ARIA (2), XSS (9), tabs keyboard (9) - ESLint + PHP CS Fixer: 0 errors - SonarQube exclusions aligned with vitest coverage config Infra: - Meilisearch consistency command (app:meilisearch:check-consistency --fix) + cron daily 3am - MeilisearchService: getAllDocumentIds(), listIndexes() Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-23 11:14:06 +01:00
it('switches active tab on click', () => {
document.querySelector('[data-tab="tab-b"]').click()
expect(document.getElementById('tab-a').style.display).toBe('none')
expect(document.getElementById('tab-b').style.display).toBe('block')
})
it('updates button styles on click', () => {
const btnA = document.querySelector('[data-tab="tab-a"]')
const btnB = document.querySelector('[data-tab="tab-b"]')
btnB.click()
expect(btnB.style.backgroundColor).toBe('#111827')
expect(btnB.style.color).toBe('white')
expect(btnA.style.backgroundColor).toBe('white')
expect(btnA.style.color).toBe('#111827')
})
it('switches back to first tab', () => {
const btnA = document.querySelector('[data-tab="tab-a"]')
const btnB = document.querySelector('[data-tab="tab-b"]')
btnB.click()
btnA.click()
expect(document.getElementById('tab-a').style.display).toBe('block')
expect(document.getElementById('tab-b').style.display).toBe('none')
})
it('does nothing without tab elements', () => {
document.body.innerHTML = ''
expect(() => initTabs()).not.toThrow()
})
})
Complete TASK_CHECKUP: security, UX, tests, coverage, accessibility, config externalization Billetterie: - Partial refund support (STATUS_PARTIALLY_REFUNDED, refundedAmount field, migration) - Race condition fix: PESSIMISTIC_WRITE lock on stock decrement in transaction - Idempotency key on PaymentIntent::create, reuse existing PI if stripeSessionId set - Disable checkout when event ended (server 400 + template hide) - Webhook deduplication via cache (24h TTL on stripe event.id) - Email validation (filter_var) in OrderController guest flow - JSON cart validation (structure check before processing) - Invitation expiration after 7 days (isExpired method + landing page message) - Stripe Checkout fallback when JS fails to load (noscript + redirect) Config externalization: - Move Stripe fees (STRIPE_FEE_RATE, STRIPE_FEE_FIXED) and admin email (ADMIN_EMAIL) to .env/services.yaml - Replace all hardcoded contact@e-cosplay.fr across 13 files - MailerService: getAdminEmail()/getAdminFrom(), default $from=null resolves to admin UX & Accessibility: - ARIA tabs: role=tablist/tab/tabpanel, aria-selected, keyboard nav (arrows, Home, End) - aria-label on cart +/- buttons and editor toolbar buttons - tabindex=0 on editor toolbar buttons for keyboard access - data-confirm handler in app.js (was only in admin.js) - Cart error feedback on checkout failure - Billet designer save feedback (loading/success/error states) - Stock polling every 30s with rupture/low stock badges - Back to event link on payment page Security: - HTML sanitizer: BLOCKED_TAGS list (script, style, iframe, svg, etc.) - content fully removed - Stripe polling timeout (15s max) with fallback redirect - Rate limiting on public order access (20/5min) - .catch() on all fetch() calls (sortable, billet-designer) Tests (92% PHP, 100% JS lines): - PCOV added to dev Dockerfile - Test DB setup: .env.test with DATABASE_URL, Redis auth, Meilisearch key - Rate limiter disabled in test env - Makefile: test_db_setup, test_db_reset, run_test_php, run_test_coverage_php/js - New tests: InvitationFlowTest (21), AuditServiceTest (4), ExportServiceTest (9), InvoiceServiceTest (4) - New tests: SuspendedUserSubscriberTest, RateLimiterSubscriberTest, MeilisearchServiceTest - New tests: Stripe webhook payment_failed (6) + charge.refunded (6) - New tests: BilletBuyer refund, User suspended, OrganizerInvitation expiration - JS tests: stock polling (6), data-confirm (2), copy-url restore (1), editor ARIA (2), XSS (9), tabs keyboard (9) - ESLint + PHP CS Fixer: 0 errors - SonarQube exclusions aligned with vitest coverage config Infra: - Meilisearch consistency command (app:meilisearch:check-consistency --fix) + cron daily 3am - MeilisearchService: getAllDocumentIds(), listIndexes() Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-23 11:14:06 +01:00
describe('ARIA attributes', () => {
beforeEach(() => setup())
Add LibreTranslate auto-translation, improve test coverage, fix code duplication Translation system: - Add LibreTranslate container (dev + prod), CPU-only, no port exposed, FR/EN/ES/DE/IT - Create app:translate command: reads *.fr.yaml, translates incrementally, preserves placeholders - Makefile: make trans / make trans_prod (stops container after translation) - Ansible: start libretranslate -> translate -> stop during deploy - Prod container restart: "no" (only runs during deploy) - .gitignore: ignore generated *.en/es/de/it.yaml files - 11 tests for TranslateCommand (API unreachable, empty, incremental, obsolete keys, placeholders, fallback) Test coverage improvements: - OrderController: event ended (400), invalid cart JSON, invalid email, stock zero (4 new tests) - AccountController: finance stats all statuses (paid/pending/refunded/cancelled), soldCounts (2 new tests) - JS cart: checkout without error elements, hide error on retry, stock polling edge cases (singular, no label, qty zero, unknown billet) (8 new tests) - JS editor: comment node sanitization (1 new test) - JS tabs: missing panel, generated id, parent null, click no-panel (5 new tests) Code duplication fixes: - MeilisearchConsistencyCommand: extract diffAndReport() method (was duplicated 3x) - Email templates: extract _order_items_table.html.twig partial (shared by notification + cancelled) - SonarQube: exclude src/Entity/** from CPD (getters/setters duplication) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-23 11:44:13 +01:00
it('handles tabs without parent element', () => {
document.body.innerHTML = `
<button data-tab="tab-x" style="background-color:#111827;color:white;">X</button>
<div id="tab-x" style="display:block;">Content X</div>
`
initTabs()
const btn = document.querySelector('[data-tab="tab-x"]')
expect(btn.getAttribute('role')).toBe('tab')
expect(document.body.getAttribute('role')).toBe('tablist')
})
it('generates id for buttons without id', () => {
document.body.innerHTML = `
<div>
<button data-tab="tab-noid" style="background-color:#111827;color:white;">No ID</button>
</div>
<div id="tab-noid" style="display:block;">Content</div>
`
initTabs()
const btn = document.querySelector('[data-tab="tab-noid"]')
expect(btn.id).toBe('tab-btn-tab-noid')
})
it('keeps existing button id', () => {
document.body.innerHTML = `
<div>
<button id="my-custom-id" data-tab="tab-keep" style="background-color:#111827;color:white;">Keep</button>
</div>
<div id="tab-keep" style="display:block;">Content</div>
`
initTabs()
expect(document.querySelector('[data-tab="tab-keep"]').id).toBe('my-custom-id')
})
it('handles missing panel gracefully', () => {
document.body.innerHTML = `
<div>
<button data-tab="tab-exists" style="background-color:#111827;color:white;">Exists</button>
<button data-tab="tab-missing" style="background-color:white;color:#111827;">Missing</button>
</div>
<div id="tab-exists" style="display:block;">Content</div>
`
initTabs()
const btnMissing = document.querySelector('[data-tab="tab-missing"]')
expect(btnMissing.getAttribute('role')).toBe('tab')
expect(btnMissing.getAttribute('aria-selected')).toBe('false')
})
it('click on tab with missing panel does not crash', () => {
document.body.innerHTML = `
<div>
<button data-tab="tab-ok" style="background-color:#111827;color:white;">OK</button>
<button data-tab="tab-nopanel" style="background-color:white;color:#111827;">No Panel</button>
</div>
<div id="tab-ok" style="display:block;">Content</div>
`
initTabs()
const btn = document.querySelector('[data-tab="tab-nopanel"]')
expect(() => btn.click()).not.toThrow()
expect(btn.getAttribute('aria-selected')).toBe('true')
})
Complete TASK_CHECKUP: security, UX, tests, coverage, accessibility, config externalization Billetterie: - Partial refund support (STATUS_PARTIALLY_REFUNDED, refundedAmount field, migration) - Race condition fix: PESSIMISTIC_WRITE lock on stock decrement in transaction - Idempotency key on PaymentIntent::create, reuse existing PI if stripeSessionId set - Disable checkout when event ended (server 400 + template hide) - Webhook deduplication via cache (24h TTL on stripe event.id) - Email validation (filter_var) in OrderController guest flow - JSON cart validation (structure check before processing) - Invitation expiration after 7 days (isExpired method + landing page message) - Stripe Checkout fallback when JS fails to load (noscript + redirect) Config externalization: - Move Stripe fees (STRIPE_FEE_RATE, STRIPE_FEE_FIXED) and admin email (ADMIN_EMAIL) to .env/services.yaml - Replace all hardcoded contact@e-cosplay.fr across 13 files - MailerService: getAdminEmail()/getAdminFrom(), default $from=null resolves to admin UX & Accessibility: - ARIA tabs: role=tablist/tab/tabpanel, aria-selected, keyboard nav (arrows, Home, End) - aria-label on cart +/- buttons and editor toolbar buttons - tabindex=0 on editor toolbar buttons for keyboard access - data-confirm handler in app.js (was only in admin.js) - Cart error feedback on checkout failure - Billet designer save feedback (loading/success/error states) - Stock polling every 30s with rupture/low stock badges - Back to event link on payment page Security: - HTML sanitizer: BLOCKED_TAGS list (script, style, iframe, svg, etc.) - content fully removed - Stripe polling timeout (15s max) with fallback redirect - Rate limiting on public order access (20/5min) - .catch() on all fetch() calls (sortable, billet-designer) Tests (92% PHP, 100% JS lines): - PCOV added to dev Dockerfile - Test DB setup: .env.test with DATABASE_URL, Redis auth, Meilisearch key - Rate limiter disabled in test env - Makefile: test_db_setup, test_db_reset, run_test_php, run_test_coverage_php/js - New tests: InvitationFlowTest (21), AuditServiceTest (4), ExportServiceTest (9), InvoiceServiceTest (4) - New tests: SuspendedUserSubscriberTest, RateLimiterSubscriberTest, MeilisearchServiceTest - New tests: Stripe webhook payment_failed (6) + charge.refunded (6) - New tests: BilletBuyer refund, User suspended, OrganizerInvitation expiration - JS tests: stock polling (6), data-confirm (2), copy-url restore (1), editor ARIA (2), XSS (9), tabs keyboard (9) - ESLint + PHP CS Fixer: 0 errors - SonarQube exclusions aligned with vitest coverage config Infra: - Meilisearch consistency command (app:meilisearch:check-consistency --fix) + cron daily 3am - MeilisearchService: getAllDocumentIds(), listIndexes() Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-23 11:14:06 +01:00
it('sets role=tablist on parent', () => {
expect(document.getElementById('tablist').getAttribute('role')).toBe('tablist')
})
it('sets role=tab on each button', () => {
document.querySelectorAll('[data-tab]').forEach(btn => {
expect(btn.getAttribute('role')).toBe('tab')
})
})
it('sets aria-controls matching panel id', () => {
const btn = document.querySelector('[data-tab="tab-b"]')
expect(btn.getAttribute('aria-controls')).toBe('tab-b')
})
it('sets role=tabpanel on panels', () => {
expect(document.getElementById('tab-a').getAttribute('role')).toBe('tabpanel')
expect(document.getElementById('tab-b').getAttribute('role')).toBe('tabpanel')
})
it('sets aria-labelledby on panels', () => {
const btnA = document.querySelector('[data-tab="tab-a"]')
expect(document.getElementById('tab-a').getAttribute('aria-labelledby')).toBe(btnA.id)
})
it('sets aria-selected=true on active tab', () => {
const btnA = document.querySelector('[data-tab="tab-a"]')
const btnB = document.querySelector('[data-tab="tab-b"]')
expect(btnA.getAttribute('aria-selected')).toBe('true')
expect(btnB.getAttribute('aria-selected')).toBe('false')
})
it('updates aria-selected on click', () => {
const btnA = document.querySelector('[data-tab="tab-a"]')
const btnB = document.querySelector('[data-tab="tab-b"]')
btnB.click()
expect(btnA.getAttribute('aria-selected')).toBe('false')
expect(btnB.getAttribute('aria-selected')).toBe('true')
})
it('sets tabindex=0 on active, -1 on inactive', () => {
const btnA = document.querySelector('[data-tab="tab-a"]')
const btnB = document.querySelector('[data-tab="tab-b"]')
expect(btnA.getAttribute('tabindex')).toBe('0')
expect(btnB.getAttribute('tabindex')).toBe('-1')
})
it('updates tabindex on click', () => {
const btnA = document.querySelector('[data-tab="tab-a"]')
const btnB = document.querySelector('[data-tab="tab-b"]')
btnB.click()
expect(btnA.getAttribute('tabindex')).toBe('-1')
expect(btnB.getAttribute('tabindex')).toBe('0')
})
})
describe('keyboard navigation', () => {
beforeEach(() => setup())
it('ArrowRight moves to next tab', () => {
const btnA = document.querySelector('[data-tab="tab-a"]')
btnA.dispatchEvent(new KeyboardEvent('keydown', { key: 'ArrowRight', bubbles: true }))
expect(document.querySelector('[data-tab="tab-b"]').getAttribute('aria-selected')).toBe('true')
expect(document.getElementById('tab-b').style.display).toBe('block')
})
it('ArrowLeft moves to previous tab', () => {
const btnB = document.querySelector('[data-tab="tab-b"]')
btnB.click()
btnB.dispatchEvent(new KeyboardEvent('keydown', { key: 'ArrowLeft', bubbles: true }))
expect(document.querySelector('[data-tab="tab-a"]').getAttribute('aria-selected')).toBe('true')
})
it('ArrowRight wraps from last to first', () => {
const btnC = document.querySelector('[data-tab="tab-c"]')
btnC.click()
btnC.dispatchEvent(new KeyboardEvent('keydown', { key: 'ArrowRight', bubbles: true }))
expect(document.querySelector('[data-tab="tab-a"]').getAttribute('aria-selected')).toBe('true')
})
it('ArrowLeft wraps from first to last', () => {
const btnA = document.querySelector('[data-tab="tab-a"]')
btnA.dispatchEvent(new KeyboardEvent('keydown', { key: 'ArrowLeft', bubbles: true }))
expect(document.querySelector('[data-tab="tab-c"]').getAttribute('aria-selected')).toBe('true')
})
it('Home moves to first tab', () => {
const btnC = document.querySelector('[data-tab="tab-c"]')
btnC.click()
btnC.dispatchEvent(new KeyboardEvent('keydown', { key: 'Home', bubbles: true }))
expect(document.querySelector('[data-tab="tab-a"]').getAttribute('aria-selected')).toBe('true')
})
it('End moves to last tab', () => {
const btnA = document.querySelector('[data-tab="tab-a"]')
btnA.dispatchEvent(new KeyboardEvent('keydown', { key: 'End', bubbles: true }))
expect(document.querySelector('[data-tab="tab-c"]').getAttribute('aria-selected')).toBe('true')
})
it('ArrowDown moves to next tab', () => {
const btnA = document.querySelector('[data-tab="tab-a"]')
btnA.dispatchEvent(new KeyboardEvent('keydown', { key: 'ArrowDown', bubbles: true }))
expect(document.querySelector('[data-tab="tab-b"]').getAttribute('aria-selected')).toBe('true')
})
it('ArrowUp moves to previous tab', () => {
const btnB = document.querySelector('[data-tab="tab-b"]')
btnB.click()
btnB.dispatchEvent(new KeyboardEvent('keydown', { key: 'ArrowUp', bubbles: true }))
expect(document.querySelector('[data-tab="tab-a"]').getAttribute('aria-selected')).toBe('true')
})
it('other keys do nothing', () => {
const btnA = document.querySelector('[data-tab="tab-a"]')
btnA.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true }))
expect(btnA.getAttribute('aria-selected')).toBe('true')
})
})