我有一个包含类似于this.$route.fullPath
的语句的组件,如果要测试该组件,应该如何模拟fullPath
对象的$route
的值?
最佳答案
最好不要模拟vue-router
,而要使用它来呈现组件,这样就可以得到一个正常工作的路由器。例:
import Vue from 'vue'
import VueRouter from 'vue-router'
import totest from 'src/components/totest'
describe('totest.vue', () => {
it('should totest renders stuff', done => {
Vue.use(VueRouter)
const router = new VueRouter({routes: [
{path: '/totest/:id', name: 'totest', component: totest},
{path: '/wherever', name: 'another_component', component: {render: h => '-'}},
]})
const vm = new Vue({
el: document.createElement('div'),
router: router,
render: h => h('router-view')
})
router.push({name: 'totest', params: {id: 123}})
Vue.nextTick(() => {
console.log('html:', vm.$el)
expect(vm.$el.querySelector('h2').textContent).to.equal('Fred Bloggs')
done()
})
})
})
注意事项:
render: h => h('router-view')
。 totest
组件,但是如果totest
引用了其他组件,则可能需要其他组件。在此示例中为another_component
。 nextTick
来呈现HTML,然后才能查看/测试它。 问题之一是,我发现的大多数示例都引用了
vue-router
的旧版本,例如the migrations docs。一些示例使用了router.go()
,该代码现在不起作用。
关于unit-testing - 如何编写在Vue组件中模拟$ route对象的测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41458736/