如何编写在Vue组件中模拟$ route对象的测试
问题描述:
我有一个包含类似于this.$route.fullPath
的语句的组件,如果要测试该组件,应该如何模拟$route
对象的fullPath
的值?
I have a component that contains statement like this.$route.fullPath
, how should I mock value of fullPath
of $route
object if I want to test that component?
答
最好不要模拟vue-router
,而是使用它来呈现组件,这样您就可以得到一个正常工作的路由器.示例:
Best not mock vue-router
but rather use it to render the component, that way you get a proper working router. Example:
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()
})
})
})
注意事项:
- 我正在使用vue的仅限运行时版本,因此是
render: h => h('router-view')
. - 我仅测试
totest
组件,但是如果totest
引用了其他组件,则可能需要其他组件.在此示例中为another_component
. - 您需要
nextTick
才能呈现HTML,然后才能对其进行查看/测试.
- I'm using the runtime-only version of vue, hence
render: h => h('router-view')
. - I'm only testing the
totest
component, but others might be required if they're referenced bytotest
eg.another_component
in this example. - You need
nextTick
for the HTML to have rendered before you can look at it/test it.
问题之一是,我发现的大多数示例都引用了vue-router
的旧版本,请参见
One of the problems is that most of the examples I found referred to the old version of vue-router
, see the migrations docs, eg. some examples use router.go()
which now doesn't work.