How to Test route from useRoute in a Vue.js 3 Composition API Component?

87 Views Asked by At

I'm facing challenges in testing a Vue.js 3 component that utilizes the useRoute from the Vue Router within the Vue Test Utils, Mocha, and Chai framework. My component is written using the Composition API syntax.

When trying to test the component, I encountered the following issue: route does not exist inside the wrapper. Here's the error message: TypeError: Cannot read properties of undefined (reading 'path').

I attempted to mock route like this:

let wrapper;
const route = { path: '/hello' };

beforeEach(() => {
  wrapper = mount(HelloWorld, {
    props: {
      msg: 'Hello!'
    },
    global: {
      mocks: {
        route
      }
    }
  });
});

This approach worked for the HelloWorld.vue component:

<script setup>
import { useRoute } from 'vue-router';

defineProps({
  msg: {
    type: String,
    required: true
  }
});

const route = useRoute();
</script>

<template>
  <div class="greetings">
    <h1 class="green">{{ route.path }}</h1>
    <h1 class="green">{{ msg }}</h1>
  </div>
</template>

But it failed for another component, as shown below. Why is this happening?

<script setup>
import { computed } from 'vue';
import { useRoute } from 'vue-router';

defineProps({
  msg: {
    type: String,
    required: true
  }
});

const route = useRoute();

const path = computed(() => {
  return route.path;
});
</script>

<template>
  <div class="greetings">
    <h1 class="green">{{ path }}</h1>
    <h1 class="green">{{ msg }}</h1>
  </div>
</template>

I would appreciate any advice or recommendations on resolving this testing issue with the Composition API component. Thank you!

0

There are 0 best solutions below