useHtmlLinks.spec.ts 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. // Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. import { createTestingPinia } from '@pinia/testing'
  3. import { useHtmlLinks } from '../useHtmlLinks.ts'
  4. const buildSampleElement = () => {
  5. const elem = document.createElement('div')
  6. elem.innerHTML = `some text
  7. <a href="http://example.com/asd" external>external</a>
  8. <a href="/desktop/test" internal>internal</a>
  9. <a href="/desktop/blank" blank target=_blank>blank</a>
  10. <a data-mention-user-id="123" mention>mention</a>
  11. her text`
  12. return elem
  13. }
  14. const routerPush = vi.fn()
  15. vi.mock('vue-router', async () => {
  16. return {
  17. useRouter: () => {
  18. return {
  19. push: routerPush,
  20. }
  21. },
  22. }
  23. })
  24. describe('setupLinkHandlers', () => {
  25. createTestingPinia({ createSpy: vi.fn })
  26. it('replaces mention links with URLs to user profile', async () => {
  27. const elem = buildSampleElement()
  28. const { setupLinksHandlers } = useHtmlLinks('/desktop')
  29. setupLinksHandlers(elem)
  30. elem.querySelector<HTMLLinkElement>('a[mention]')?.click()
  31. expect(routerPush).toHaveBeenCalledWith('/users/123')
  32. })
  33. it('opens internal link via the router', () => {
  34. const elem = buildSampleElement()
  35. const { setupLinksHandlers } = useHtmlLinks('/desktop')
  36. setupLinksHandlers(elem)
  37. elem.querySelector<HTMLLinkElement>('a[internal]')?.click()
  38. expect(routerPush).toHaveBeenCalledWith('/test')
  39. })
  40. it('opens internal _blank link in a new tab', () => {
  41. vi.stubGlobal('open', vi.fn())
  42. const spy = vi.spyOn(window, 'open')
  43. const elem = buildSampleElement()
  44. const { setupLinksHandlers } = useHtmlLinks('/desktop')
  45. setupLinksHandlers(elem)
  46. elem.querySelector<HTMLLinkElement>('a[blank]')?.click()
  47. expect(spy).toHaveBeenCalledWith('/desktop/blank', '_blank')
  48. })
  49. it('opens external link directly', () => {
  50. vi.stubGlobal('open', vi.fn())
  51. const spy = vi.spyOn(window, 'open')
  52. const elem = buildSampleElement()
  53. const { setupLinksHandlers } = useHtmlLinks('/desktop')
  54. setupLinksHandlers(elem)
  55. elem.querySelector<HTMLLinkElement>('a[external]')?.click()
  56. expect(routerPush).not.toHaveBeenCalled()
  57. expect(spy).not.toHaveBeenCalled()
  58. })
  59. })