In the combined API unit test of Vue 3, it was found that $route was not defined in the onMounted() hook
P粉668146636
P粉668146636 2023-08-26 08:54:29
0
1
427
<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粉668146636
P粉668146636

reply all(1)
P粉739079318

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!