问题描述
我有一个包含像 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 by totest
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
,请参阅迁移文档,例如.一些示例使用 router.go()
现在不起作用.
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.
这篇关于如何编写模拟 vue 组件中的 $route 对象的测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论