utils.test.ts 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. import { afterEach, beforeEach, describe, expect, it } from 'vitest'
  2. import {
  3. focusFirstDescendant,
  4. getEdges,
  5. obtainAllFocusableElements,
  6. } from '../src/utils'
  7. describe('focus-trap utils', () => {
  8. const buildDOM = () => {
  9. const parser = new DOMParser()
  10. return parser.parseFromString(
  11. `
  12. <div class="root">
  13. <span>some val</span>
  14. <input class="focusable-input" />
  15. <span tabindex="0" class="focusable-span">other val</span>
  16. <span hidden tabindex="0"> hidden span</span>
  17. <input disabled />
  18. <input hidden />
  19. </div>
  20. `,
  21. 'text/html'
  22. )
  23. }
  24. beforeEach(() => {
  25. const dom = buildDOM()
  26. Array.from(dom.children).forEach((child) => {
  27. document.body.appendChild(child)
  28. })
  29. })
  30. afterEach(() => {
  31. document.body.innerHTML = ''
  32. })
  33. it('should be able to focus', () => {
  34. const focusable = obtainAllFocusableElements(document.body)
  35. expect(focusable).toHaveLength(2)
  36. expect(focusable[0].classList.contains('focusable-input')).toBeTruthy()
  37. })
  38. it('should be able to get focusable edge', () => {
  39. const [first, last] = getEdges(document.body)
  40. expect(first?.classList.contains('focusable-input')).toBeTruthy()
  41. expect(last?.classList.contains('focusable-span')).toBeTruthy()
  42. })
  43. it('should be able to focus on the first descendant', () => {
  44. expect(document.activeElement).toBe(document.body)
  45. const focusable = obtainAllFocusableElements(document.body)
  46. focusFirstDescendant(focusable)
  47. expect(document.activeElement).toBe(focusable[0])
  48. })
  49. })