Утилиты тестирования Vue с Vue-router4 и Vue3 Composition API

Я не могу смонтировать компонент во время модульного тестирования из-за того, что объект маршрута не определен в методе настройки во время монтирования. Руководства, похоже, нацелены на Vue2 и API параметров.

Ссылки:

Как написать тест, который имитирует объект $ route в компонентах vue
Как выполнить модульное тестирование с помощью jest в компоненте api композиции vue?
https://vue-test-utils.vuejs.org/guides/#using-with-typescript
https://vue-test-utils.vuejs.org/guides/#using-with-vue-router

Ошибка

● CoachItem.vue › displays alert when item is clicked

    TypeError: Cannot read property 'path' of undefined

      64 |       fullName: computed(() => props.firstName + " " + props.lastName),
      65 |       coachContactLink: computed(
    > 66 |         () => route.path + "/" + props.id + "/contact"

// @/tests/unit/example.spec.ts

import CoachItem from "@/components/coaches/CoachItem.vue"
import router from "@/router"


  describe("CoachItem.vue", () => {
    it("displays alert when item is clicked", async () => {

      //const route = { path: 'http://www.example-path.com' }
      router.push('/')
      await router.isReady()
      const wrapper = mount(CoachItem); //adding this line causes failure
      //await wrapper.trigger('click');
      //const dialog = wrapper.find('dialog');
      //(dialog.exists()).toBeTruthy()
    })
  })
// @/components/UserAlert.vue

<template>
  <div class="backdrop" @click="closeDialog"></div>
  <dialog open>
    <header>
      <h2>{{ title }}</h2>
    </header>
    <div>
      <slot name="content"></slot>
    </div>
    <menu>
      <button @click="closeDialog">Close</button>
    </menu>
  </dialog>
</template>

<script lang="ts>
import { defineComponent } from "vue";

export default defineComponent({
  props: ['title'],
  emits: ['close'],
  setup(_, context) {
    function closeDialog() {
      context.emit('close');
    }

    return { closeDialog };
  },
});
</script>
// @/components/coaches.CoachItem.vue

<template>
<user-alert v-if="alertIsVisible" title="Alert!" @close="hideAlert">
    <template v-slot:content><p>this is a slot</p></template>
  </user-alert>
  <li @click="showAlert">
    <h3>{{ fullName }}</h3>
    <h4>${{ rate }}/hour</h4>
    <div>
      <base-badge
        v-for="area in areas"
        :key="area"
        :type="area"
        :title="area"
      ></base-badge>
    </div>
    <div class="actions">
      <base-button mode="outline" link :to="coachContactLink"
        >Contact</base-button
      >
      <base-button link :to="coachDetailsLink">View Details</base-button>
    </div>
  </li>
</template>

<script lang="ts">
import { computed, defineComponent, PropType, ref } from "vue";
import { useRoute } from "vue-router";
import useAlert from "../../components/hooks/useAlert";
export default defineComponent({
  props: {
    id: {
      type: String,
      required: true,
    },
    firstName: {
      type: String,
      required: true,
    },
    lastName: {
      type: String,
      required: true,
    },
    rate: {
      type: Number,
      required: true,
    },
    areas: {
      type: Object as PropType<Array<string>>,
      required: true,
    },
  },
  setup(props) {
    const route = useRoute();
    const alertTitle = ref("delete user?");
    return {
      fullName: computed(() => props.firstName + " " + props.lastName),
      coachContactLink: computed(
        () => route.path + "/" + props.id + "/contact"
      ),
      coachDetailsLink: computed(() => route.path + "/" + props.id),
      ...useAlert()
    };
  },
});
</script>
// @/main.ts
import { createApp } from "vue";
import App from "./App.vue";
import router from "./router";
import {store, key }  from "./store";
import UserAlert from "@/components/UserAlert.vue";

createApp(App)
.component('UserAlert', UserAlert)
  .use(store, key)
  .use(router)
  .mount("#app");
// @/router/index.ts

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
});

export default router;

person user1232345    schedule 06.01.2021    source источник
comment
Ссылки на документацию, которыми вы делитесь, принадлежат Vue2.x, вам необходимо проверить в этом документе.   -  person Eldar    schedule 06.01.2021
comment
@Eldar Эти примеры маршрутизатора Vue для Vue3.x, похоже, также используют API параметров, к сожалению   -  person user1232345    schedule 06.01.2021