use-attrs.test.tsx 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. import { computed, defineComponent } from 'vue'
  2. import { mount } from '@vue/test-utils'
  3. import { afterEach, describe, expect, it, vi } from 'vitest'
  4. import { useAttrs } from '../use-attrs'
  5. import type { ComputedRef } from 'vue'
  6. const CLASS = 'a'
  7. const WIDTH = '50px'
  8. const TEST_KEY = 'test'
  9. const TEST_VALUE = 'fake'
  10. const ANOTHER_TEST_VALUE = 'fake1'
  11. const handleClick = vi.fn()
  12. const genComp = (
  13. inheritAttrs = true,
  14. excludeListeners = false,
  15. excludeKeys?: ComputedRef<string[]>
  16. ) => {
  17. return defineComponent({
  18. inheritAttrs,
  19. props: {} as Record<string, any>,
  20. setup() {
  21. const attrs = useAttrs({ excludeListeners, excludeKeys })
  22. return () => (
  23. <div>
  24. <span {...attrs.value} />
  25. </div>
  26. )
  27. },
  28. })
  29. }
  30. const _mount = (Comp: ReturnType<typeof genComp>) => {
  31. return mount({
  32. setup() {
  33. return () => (
  34. <Comp
  35. class={CLASS}
  36. style={{ width: WIDTH }}
  37. onClick={handleClick}
  38. {...{ [TEST_KEY]: TEST_VALUE }}
  39. />
  40. )
  41. },
  42. })
  43. }
  44. describe('useAttrs', () => {
  45. afterEach(() => {
  46. vi.restoreAllMocks()
  47. })
  48. it('class and style should not bind to child node', async () => {
  49. const wrapper = _mount(genComp())
  50. const container = wrapper.element as HTMLDivElement
  51. const span = wrapper.find('span')
  52. expect(wrapper.classes(CLASS)).toBe(true)
  53. expect(container.style.width).toBe(WIDTH)
  54. expect(span.classes(CLASS)).toBe(false)
  55. expect(span.element.style.width).toBe('')
  56. expect(span.attributes(TEST_KEY)).toBe(TEST_VALUE)
  57. await span.trigger('click')
  58. expect(handleClick).toBeCalledTimes(2)
  59. })
  60. it("child node's attributes should update when prop change", async () => {
  61. const wrapper = _mount(genComp())
  62. const span = wrapper.find('span')
  63. await wrapper.setProps({ [TEST_KEY]: ANOTHER_TEST_VALUE })
  64. expect(span.attributes(TEST_KEY)).toBe(ANOTHER_TEST_VALUE)
  65. })
  66. it('excluded listeners should not bind to child node', async () => {
  67. const wrapper = _mount(genComp(true, true))
  68. const span = wrapper.find('span')
  69. await span.trigger('click')
  70. expect(handleClick).toBeCalledTimes(1)
  71. })
  72. it('excluded attributes should not bind to child node', async () => {
  73. const wrapper = _mount(
  74. genComp(
  75. true,
  76. false,
  77. computed(() => [TEST_KEY])
  78. )
  79. )
  80. const span = wrapper.find('span')
  81. expect(span.attributes(TEST_KEY)).toBeUndefined()
  82. })
  83. })