use-floating.test.tsx 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. import { computed, nextTick, reactive, ref, watch } from 'vue'
  2. import { mount } from '@vue/test-utils'
  3. import { describe, expect, it } from 'vitest'
  4. import { rAF } from '@element-plus/test-utils/tick'
  5. import { arrowMiddleware, useFloating } from '../use-floating'
  6. import type { CSSProperties } from 'vue'
  7. import type { Middleware, Placement, Strategy } from '@floating-ui/dom'
  8. describe('useFloating', () => {
  9. const createComponent = (arrow = false) => {
  10. return mount({
  11. setup() {
  12. const placement = ref<Placement>('bottom')
  13. const strategy = ref<Strategy>('fixed')
  14. const arrowRef = ref<HTMLElement>()
  15. const middleware = ref<Array<Middleware>>(
  16. arrow
  17. ? [
  18. arrowMiddleware({
  19. arrowRef,
  20. }),
  21. ]
  22. : []
  23. )
  24. const { referenceRef, contentRef, x, y, update, middlewareData } =
  25. useFloating({
  26. placement,
  27. strategy,
  28. middleware,
  29. })
  30. const contentStyle = computed<CSSProperties>(() => {
  31. return reactive({
  32. position: strategy,
  33. x,
  34. y,
  35. })
  36. })
  37. watch(arrowRef, () => update())
  38. return {
  39. arrowRef,
  40. contentRef,
  41. contentStyle,
  42. referenceRef,
  43. middlewareData,
  44. }
  45. },
  46. render() {
  47. const { contentStyle } = this
  48. return (
  49. <div>
  50. <button ref="referenceRef">My button</button>
  51. <div ref="contentRef" style={contentStyle}>
  52. My tooltip
  53. <div ref="arrowRef" />
  54. </div>
  55. </div>
  56. )
  57. },
  58. })
  59. }
  60. let wrapper: ReturnType<typeof createComponent>
  61. it('should render without arrow correctly', async () => {
  62. wrapper = createComponent()
  63. await rAF()
  64. await nextTick()
  65. expect(wrapper.vm.referenceRef).toBeInstanceOf(Element)
  66. expect(wrapper.vm.contentRef).toBeInstanceOf(Element)
  67. expect(wrapper.vm.middlewareData.arrow).toBeUndefined()
  68. })
  69. it('should render with arrow correctly', async () => {
  70. wrapper = createComponent(true)
  71. await rAF()
  72. await nextTick()
  73. expect(wrapper.vm.referenceRef).toBeInstanceOf(Element)
  74. expect(wrapper.vm.contentRef).toBeInstanceOf(Element)
  75. expect(wrapper.vm.middlewareData.arrow).toBeDefined()
  76. })
  77. })