useTouchDevice.spec.ts 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. // Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. import { useTouchDevice } from '../useTouchDevice.ts'
  3. const mockPointerCoarseMediaQuery = (initialMatchesQuery = false) => {
  4. let matchesQuery = initialMatchesQuery
  5. let observeCallback = vi.fn()
  6. // Impersonate a touch device state by mocking the corresponding media query in a dynamic manner.
  7. Object.defineProperty(window, 'matchMedia', {
  8. value: vi.fn().mockImplementation((query: string) => {
  9. if (query !== '(pointer: coarse)') return
  10. return {
  11. matches: matchesQuery,
  12. addEventListener: vi.fn().mockImplementation((type, listener) => {
  13. if (type !== 'change') return
  14. observeCallback = listener
  15. }),
  16. removeEventListener: vi.fn(),
  17. }
  18. }),
  19. })
  20. return (newMatchesQuery: boolean) => {
  21. matchesQuery = newMatchesQuery
  22. observeCallback()
  23. }
  24. }
  25. describe('isTouchDevice', () => {
  26. it('returns false for non-touch devices', () => {
  27. mockPointerCoarseMediaQuery(false)
  28. const { isTouchDevice } = useTouchDevice()
  29. expect(isTouchDevice.value).toBe(false)
  30. })
  31. it('returns true for non-touch devices', () => {
  32. mockPointerCoarseMediaQuery(true)
  33. const { isTouchDevice } = useTouchDevice()
  34. expect(isTouchDevice.value).toBe(true)
  35. })
  36. it('reacts to touch media query changes', () => {
  37. const changePointerCoarseMediaQuery = mockPointerCoarseMediaQuery()
  38. const { isTouchDevice } = useTouchDevice()
  39. expect(isTouchDevice.value).toBe(false)
  40. changePointerCoarseMediaQuery(true)
  41. expect(isTouchDevice.value).toBe(true)
  42. })
  43. })