@700Hp

Как писать unit тесты vue компонетов если в проекте используется vuetify 3?

Приветствую! Код ниже - код моего компонента, я использую внутри компоненты vuetify 3.
Его нужно протестировать с использованием vue-test-utils. Но при выполнении теста постоянно падаёт ошибка ( последний скрин)

<script setup>
  import VCustomIcon from '@/modules/customIcon/VCustomIcon'
  import TextCorrecter from '@/extension/TextCorrecter'
  import { useAlertStore } from '@/store/alert/useAlertStore'
  import { storeToRefs } from 'pinia'
  import { computed } from 'vue'

  const messages = {
    'warn': 'Внимание!',
    'error': 'Сообщение об ошибке',
    'success': 'Одобрение',
    'info': 'Информация'
  }

  const store = useAlertStore()
  const { isShow, valuesAlert } = storeToRefs(store)
  const getTitle = computed(() => messages[valuesAlert.value.type])
</script>


<template>
  <transition name='slide-fade'>
    <v-alert
      v-if='isShow'
      :data-type='valuesAlert.type'
      @click='store.closeAlert'
      class='alert border-radius-0'
      color='white'
    >
      <template #default>
        <span :class='["alert-signal", valuesAlert.type]'></span>
      </template>
      <template #title>
        <div class='d-flex align-center mb-3 alert__title'>
          <v-custom-icon
            :icon-name='TextCorrecter.capitalize(valuesAlert.type) + "Alert"'
            width='36'
            height='36'
            class='mr-2'
          />
          {{ getTitle }}
        </div>
      </template>

      <template #text>
        <div class='alert__text'>{{ valuesAlert.text }}</div>
      </template>
    </v-alert>
  </transition>
</template>


jest.config.js
module.exports = {
  moduleFileExtensions: ['js', 'json', 'vue'],
  testEnvironment: 'jsdom',
  testEnvironmentOptions: {
    customExportConditions: ['node', 'node-addons']
  },
  moduleNameMapper: {
    '^@root(.*)$': '<rootDir>/src$1',
    '^@components(.*)$': '<rootDir>/src/components$1'
  },
  moduleDirectories: ['node_modules', 'src'],
  transformIgnorePatterns: [],
  transform: {
    '^.+\\.(js|jsx|mjs)$': 'babel-jest',
    '^.+\\.vue$': '@vue/vue3-jest'
  },
  setupFilesAfterEnv: ['@testing-library/jest-dom/extend-expect']
}


babel.config.js

module.exports = {
  presets: [['@babel/preset-env']],
  plugins: [
    [
      'module-resolver',
      {
        root: ['./'],
        alias: {
          '@': './src'
        }
      }
    ]
  ],
  env: {
    test: {
      presets: [['@babel/preset-env']]
    }
  }
}


Мой тест выглядит так

import { mount } from '@vue/test-utils'
import Alert from '@/components/ui/alert/VAlertCustom.vue'
import VCustomIcon from '@/modules/customIcon/VCustomIcon.vue'
import { setActivePinia, createPinia } from 'pinia'
import { useAlertStore } from '@/store/alert/useAlertStore'
import { nextTick } from 'vue'

const factory = (props = {}, attrs = {}) => {
  setActivePinia(createPinia())
  const store = useAlertStore()
  store.setAlert({
    type: 'success',
    text: 'This is a success message'
  })

  return mount(Alert, {
    global: {
      components: {
        'v-custom-icon': VCustomIcon
      }
    },
    props,
    attrs
  })
}

describe('Alert', () => {
  it('should render correctly with different message types', async () => {
    const wrapper = factory()
    expect(wrapper.exists()).toBe(true)

    await nextTick()

    expect(wrapper.find('.alert').exists()).toBe(true)
    expect(wrapper.find('.success.alert-signal').exists()).toBe(true)
    expect(wrapper.find('.alert__title').text()).toContain('Одобрение')
    expect(wrapper.find('.alert__text').text()).toContain(
      'This is a success message'
    )
  })
})


При его выполнение падаёт ошибка
647862c53b595187911347.png

Всю голову сломал. ChatGpt живёт ещё 21 годом и подсказывает не рабочие варианты (
  • Вопрос задан
  • 112 просмотров
Пригласить эксперта
Ответы на вопрос 1
@Mawriks
В общем нужно подключить в moutn vuetify.
Ниже есть пример, как сделать кастомный mount.
import * as components from "vuetify/components";
import * as directives from "vuetify/directives";

const vuetify = createVuetify({
	components,
	directives,
});

export const customMount = (
	component: any,
	options: RenderOptions | undefined = {},
	globalOptions: any = {},
) => {
	return mount(component, {
		...options,
		global: {
			plugins: [vuetify],
			...globalOptions,
		},
	});
};
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы