使用Jest对Vue.js路由进行单元测试:如何Mock页面?
解决Vue路由单元测试中仅加载欢迎页的问题
刚接触Jest和Vue测试遇到这种问题很正常,咱们一步步排查解决:
1. 修复路由守卫的Mock,让导航能正常放行
你当前对路由守卫的mock只是创建了空的jest.fn(),但beforeEnter守卫必须调用next()才能完成导航流程——如果不调用next(),导航会直接被卡住,自然一直停留在初始的Welcome页面。
把守卫的mock改成这样:
jest.mock('@/router/guards.js', () => ({ requireUser: jest.fn((to, from, next) => next()), requireFullUser: jest.fn((to, from, next) => next()), requireCurrentProject: jest.fn((to, from, next) => next()), requireSelectedProperty: jest.fn((to, from, next) => next()) }))
这样每个守卫都会主动调用next(),允许路由跳转继续执行。
2. 等待异步导航完成后再做断言
Vue Router的router.push是异步操作,你刚执行完push就立刻断言DOM,此时路由还没切换完成、DOM也没更新,所以看到的还是之前的Welcome组件。
修改测试用例,用async/await等待导航和DOM更新:
describe('can load the root of my home', () => { it('via a path', async () => { await router.push('/KT18%207LJ/1/3%20The%20Crescent/') // 等待Vue更新DOM await wrapper.vm.$nextTick() console.log(wrapper.html()) expect(wrapper.findComponent({ name: 'MyHome' }).exists()).toBeTruthy() expect(wrapper.findComponent({ name: 'MainHeader' }).exists()).toBeTruthy() }) it('via a name with parameters', async () => { await router.push({ name: 'MyHome', params: { id: 1, postcode: 'KT18 7LJ', address: '3 The Crescent' } }) await wrapper.vm.$nextTick() console.log(wrapper.html()) expect(wrapper.findComponent({ name: 'MyHome' }).exists()).toBeTruthy() expect(wrapper.findComponent({ name: 'MainHeader' }).exists()).toBeTruthy() }) })
我还把find(Views.MyHome)改成了findComponent({ name: 'MyHome' })——直接引用组件对象有时会因为mock模块的引用关系导致匹配失败,用组件name查找更稳定可靠。
3. 确认测试环境的独立性
你已经在beforeEach里重新创建了router和wrapper,这部分做得很对,保证了每个测试都有独立的路由环境,无需修改。
按这几步调整后,应该就能正常测试其他路由了!
内容的提问来源于stack exchange,提问作者Keith Jackson
相关产品推荐
相关产品推荐

