如何测试路由独享守卫的“中断”逻辑?
解读
在国内前端面试中,Vue 技术栈占主流,Vue Router 的“路由独享守卫”——beforeEnter——常被用来做权限、白名单、灰度等“中断”逻辑。所谓“中断”就是守卫里调用 next(false) 或 next('/403'),强行终止当前导航。
面试官问这道题,不是让你背诵 API,而是考察三件事:
- 能不能把“导航”抽象成纯函数,剥离对真实浏览器、真实路由实例的依赖;
- 会不会用 Jest 做“行为”断言——导航到底有没有被中断、参数有没有被改写;
- 是否熟悉 Vue Router 4 的异步导航解析流程,测试用例能不能等到导航结果落定再断言,避免“假绿”。
知识点
- Vue Router 4 的导航解析流程:守卫链 → 路由记录 → 异步组件 → 确认/中断。
- 路由守卫的三种 next:
- next() 放行;
- next(false) 中断并重置 URL;
- next(path) 中断并跳转新地址。
- Jest 对异步代码的三种写法:done 回调、返回 Promise、async/await。
- Vue Router 提供的内存历史模式(createMemoryHistory)+ 路由实例(createRouter)可在 Node 环境跑通完整导航,无需 JSDOM。
- 测试“中断”行为的核心是“结果导向”:
- 断言当前路由对象 matched 数组长度是否为 0;
- 断言 router.currentRoute.value.fullPath 是否回退或重定向;
- 断言导航方法(push/replace)是否 reject 了特定错误 NavigationFailure。
- 用 jest.spyOn 做副作用打点,确保守卫里埋的上报、弹窗、store 提交被精确调用。
- 用 flushPromises 或 router.isReady() 等待微任务队列清空,防止“导航尚未完成”导致的竞态。
答案
下面给出一份可直接在 Jest 26+ 运行的最小可运行代码,覆盖“中断并重定向”与“中断并回退”两条分支。
目录结构(Vite + Vue3 项目常见结构):
src/router/guard.js
src/router/index.js
tests/unit/guard.spec.js
guard.js —— 把守卫拆成纯函数,方便单测:
export function requireAuth(to, from, next) { const token = localStorage.getItem('token') if (!token) { // 中断并重定向到登录页 next('/login?redirect=' + encodeURIComponent(to.fullPath)) } else { next() } }
export function whiteList(to, from, next) { const white = ['/404', '/login'] if (white.includes(to.path)) { next() } else { // 中断并回退 next(false) } }
index.js —— 正常注册路由:
import { createRouter, createMemoryHistory } from 'vue-router' import Home from '@/views/Home.vue' import { requireAuth } from './guard'
const routes = [ { path: '/admin', component: () => import('@/views/Admin.vue'), beforeEnter: requireAuth }, { path: '/login', component: () => import('@/views/Login.vue') } ]
export function createTestRouter() { return createRouter({ history: createMemoryHistory(), routes }) }
guard.spec.js —— 真正的测试文件:
import { requireAuth, whiteList } from '@/router/guard' import { createTestRouter } from '@/router' import { nextTick } from 'vue'
// 工具:等待所有导航副作用落定 const flushPromises = () => new Promise(resolve => setImmediate(resolve))
describe('路由独享守卫 - 中断逻辑', () => { let router
beforeEach(() => { router = createTestRouter() localStorage.clear() })
afterEach(() => { jest.restoreAllMocks() })
it('token 不存在时中断导航并重定向到登录页', async () => { // 模拟导航 const pushLogin = jest.spyOn(router, 'push') await router.push('/admin') // 会触发 beforeEnter await flushPromises()
// 断言:当前路由不是 /admin,而是 /login
expect(router.currentRoute.value.path).toBe('/login')
expect(router.currentRoute.value.query.redirect).toBe('/admin')
// 断言:matched 为空,说明 /admin 被中断
expect(router.currentRoute.value.matched.some(m => m.path === '/admin')).toBe(false)
})
it('token 存在时正常放行', async () => { localStorage.setItem('token', 'fake-token') await router.push('/admin') await flushPromises() expect(router.currentRoute.value.path).toBe('/admin') expect(router.currentRoute.value.matched.some(m => m.path === '/admin')).toBe(true) })
it('白名单外路径调用 next(false) 中断并回退', async () => { // 先跳到一个已存在的路由,确保 from 有值 await router.push('/login') await flushPromises()
// 注册一个临时路由,使用 whiteList 守卫
router.addRoute({
path: '/secret',
beforeEnter: whiteList,
component: { template: '<div>secret</div>' }
})
// 再次触发导航
await router.push('/secret')
await flushPromises()
// 断言:URL 被重置回 /login
expect(router.currentRoute.value.path).toBe('/login')
// 断言:NavigationFailure 类型为 4(aborted)
const failures = router.getRoutes().flatMap(r => r.meta.__navigationFailure)
// 更严谨的做法是监听 onError
const onError = jest.fn()
router.onError(onError)
await router.push('/secret')
await flushPromises()
expect(onError).toHaveBeenCalledWith(
expect.objectContaining({
type: 4, // NavigationFailureType.aborted
from: expect.objectContaining({ path: '/login' }),
to: expect.objectContaining({ path: '/secret' })
})
)
}) })
运行:
npm run test:unit guard.spec.js
全部通过即证明“中断”逻辑被正确测试。
拓展思考
- 如果项目用 React Router 6,思路完全一致:把 loader 或 beforeLoad 抽象成纯函数,用 createMemoryHistory + renderHook 做导航断言。
- 对于“全局守卫”或“组件内守卫”,测试策略一样,但需要在 router.beforeEach 或 setup 里注册,断言时观察 router.currentRoute 变化即可。
- 当守卫里包含异步请求(如拉取用户权限接口)时,务必 mock 掉 axios/fetch,返回立即 resolve 的 Promise,否则测试会超时;同时用 await router.isReady() 等待导航完成。
- 为了提升 CI 速度,可把路由测试拆成“纯函数单测”+“集成导航测”两层:纯函数只测 next 调用参数,毫秒级;集成测再跑真实导航,秒级。
- 如果公司用微前端 qiankun,主应用和子应用都有守卫,测试时要分别 createMemoryHistory,防止路由实例污染;也可在 jest.setup.js 里把 window.history 替换成 memory 实现,做到“零副作用”。