In the combined API unit test of Vue 3, it was found that $route was not defined in the onMounted() hook
<p>I have a <code>onMounted()</code> hook in my component's <code>setup()</code> function, which accesses <code>$route. params</code> attribute, but when I mock the <code>$route</code> object in my test, the <code>$route</ in the <code>onMounted()</code> hook code> is <code>undefined</code>, so an error is thrown. Here is the code: </p>
<p><strong>Component.vue:</strong></p>
<pre class="brush:php;toolbar:false;"><template>
<div>{{ this.$route.params.id }}</div>
</template>
<script lang="ts">
import {defineComponent, onMounted} from 'vue'
import {useRoute} from "vue-router";
export default defineComponent({
name: 'Component',
setup() {
const route = useRoute()
onMounted(() => {
console.log(route.params.id)
})
return {}
}
})
</script></pre>
<p><strong>component.spec.ts:</strong></p>
<pre class="brush:php;toolbar:false;">import {mount} from "@vue/test-utils";
import Component from "@/views/Bundle/Component.vue";
test('test description', async () => {
const mockRoute = {
params: {
ID: 1
}
}
const mockRouter = {
push: jest.fn()
}
const wrapper = mount(Component, {
global: {
mocks: {
$route: mockRoute,
$router: mockRouter
}
}
})
await wrapper.find('button').trigger('click')
})</pre>
<p><strong>Throws error: </strong> TypeError: Cannot read property 'params' of undefined</p>
<p>I am using vue-test-utils version 2.0.0-rc.12. </p>
<p>Any help would be greatly appreciated</p>