Home  >  Q&A  >  body text

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>
P粉668146636P粉668146636419 days ago428

reply all(1)I'll reply

  • P粉739079318

    P粉7390793182023-08-27 07:27:05

    The problem is that when using the composite API, the mount options (and therefore also the $route and $router simulations) are not taken into account.

    For example, when you look at the route's matched property (in the component), the array will be empty because there are no matching routes and no routing context available. But they updated the documentation and you can see an example there.

    I wonder if there is a non-imperative way to simulate each test...

    Mock routing using composition API

    reply
    0
  • Cancelreply