avatar.test.tsx 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. import { markRaw, nextTick } from 'vue'
  2. import { mount } from '@vue/test-utils'
  3. import { describe, expect, test } from 'vitest'
  4. import { User } from '@element-plus/icons-vue'
  5. import {
  6. IMAGE_FAIL,
  7. IMAGE_SUCCESS,
  8. mockImageEvent,
  9. } from '@element-plus/test-utils/mock'
  10. import Avatar from '../src/avatar.vue'
  11. describe('Avatar.vue', () => {
  12. mockImageEvent()
  13. test('render test', () => {
  14. const wrapper = mount(() => <Avatar />)
  15. expect(wrapper.find('.el-avatar').exists()).toBe(true)
  16. })
  17. test('size is number', () => {
  18. const wrapper = mount(() => <Avatar size={50} />)
  19. expect(wrapper.attributes('style')).toContain('--el-avatar-size: 50px;')
  20. })
  21. test('size is string', () => {
  22. const wrapper = mount(() => <Avatar size="small" />)
  23. expect(wrapper.classes()).toContain('el-avatar--small')
  24. })
  25. test('shape', () => {
  26. const wrapper = mount(() => <Avatar size="small" shape="square" />)
  27. expect(wrapper.classes()).toContain('el-avatar--square')
  28. })
  29. test('icon avatar', () => {
  30. const wrapper = mount(() => <Avatar icon={markRaw(User)} />)
  31. expect(wrapper.classes()).toContain('el-avatar--icon')
  32. expect(wrapper.findComponent(User).exists()).toBe(true)
  33. })
  34. test('image avatar', () => {
  35. const wrapper = mount(() => <Avatar src={IMAGE_SUCCESS} />)
  36. expect(wrapper.find('img').exists()).toBe(true)
  37. })
  38. test('image fallback', async () => {
  39. const wrapper = mount(
  40. <Avatar
  41. src={IMAGE_FAIL}
  42. v-slots={{
  43. default: () => 'fallback',
  44. }}
  45. />
  46. )
  47. await nextTick()
  48. expect(wrapper.emitted('error')).toBeDefined()
  49. await nextTick()
  50. expect(wrapper.text()).toBe('fallback')
  51. expect(wrapper.find('img').exists()).toBe(false)
  52. })
  53. test('image fit', () => {
  54. const fits = ['fill', 'contain', 'cover', 'none', 'scale-down'] as const
  55. for (const fit of fits) {
  56. const wrapper = mount(() => <Avatar fit={fit} src={IMAGE_SUCCESS} />)
  57. expect(wrapper.find('img').attributes('style')).toContain(
  58. `object-fit: ${fit};`
  59. )
  60. }
  61. })
  62. test('src changed', async () => {
  63. const wrapper = mount(
  64. <Avatar
  65. v-slots={{
  66. default: () => 'fallback',
  67. }}
  68. />
  69. )
  70. expect(wrapper.vm.hasLoadError).toBe(false)
  71. await wrapper.setProps({ src: IMAGE_FAIL })
  72. // wait error event trigger
  73. await nextTick()
  74. expect(wrapper.vm.hasLoadError).toBe(true)
  75. await wrapper.setProps({ src: IMAGE_SUCCESS })
  76. expect(wrapper.vm.hasLoadError).toBe(false)
  77. expect(wrapper.find('img').exists()).toBe(true)
  78. })
  79. })