在 Vue 单元测试中挂载带子路由的组件,需创建配置了嵌套路由的真实 router 实例并用 mount 挂载父组件;子路由通过 router.push() 主动导航或默认空 path 子路由触发渲染。

在 Vue 单元测试中挂载带子路由的组件,关键不是“只测子组件”,而是让整个嵌套路由上下文可运行——即父组件的 能正确渲染匹配的子路由组件。这需要模拟 vue-router 的完整嵌套行为,而非简单 shallowMount。
确保测试环境有完整的 router 实例
不能只传一个空 router 或 mock 的 $route;必须创建真实配置了嵌套路由的 createRouter 实例,并注入测试应用:
- 使用
createMemoryHistory()(非浏览器环境推荐),避免依赖 window.location - routes 配置需包含父子层级,子路由 path 不加 /,例如
{ path: 'profile', component: UserProfile }(完整路径为/user/123/profile) - 父组件模板中必须含
,否则子路由无处渲染
挂载时用 mount + router 插件
使用 mount(非 shallowMount),并显式传入配置好的 router:
import { createRouter, createMemoryHistory } from 'vue-router'
import { mount } from '@vue/test-utils'
import UserLayout from '@/views/UserLayout.vue'
import UserProfile from '@/views/UserProfile.vue'
const router = createRouter({
history: createMemoryHistory(),
routes: [
{
path: '/user/:id',
component: UserLayout,
children: [
{ path: 'profile', component: UserProfile }
]
}
]
})
// 挂载父组件,同时触发子路由匹配
const wrapper = mount(UserLayout, {
global: {
plugins: [router]
},
props: { id: '123' }
})
此时访问 /user/123/profile 会自动激活 UserProfile 并渲染在 UserLayout 的 中。
主动导航到子路由路径(推荐)
若需验证特定子路由状态,可在挂载后调用 router.push() 触发匹配:
await router.push('/user/123/profile')-
await wrapper.vm.$nextTick()确保 DOM 更新完成 - 再断言
wrapper.findComponent(UserProfile)是否存在或内容是否正确
注意动态参数与默认子路由
若父路由无子路由匹配(如仅访问 /user/123),子 为空。可配置空 path 子路由作为默认页:
{
path: '', // 匹配 /user/123
component: UserHome
}
这样即使不显式跳转,父组件挂载后也能看到默认子内容,便于基础结构测试。
前端入门到VUE实战笔记:立即使用
在学习笔记中,你将探索 前端 的入门与实战技巧!










