Jer*_*ang 24 unit-testing sinon vue-component vue-loader vuejs2
我有一个包含类似语句成分this.$route.fullPath,我应该怎么嘲笑的值fullPath的$route对象,如果我想测试组件?
SCo*_*vin 32
最好不要模拟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()
})
})
})
Run Code Online (Sandbox Code Playgroud)
注意事项:
render: h => h('router-view').totest组件,但如果它们被totest例如引用,则可能需要其他组件.another_component在这个例子中.nextTick先渲染HTML才能查看/测试它.其中一个问题是我发现的大多数示例都提到了旧版本vue-router,请参阅迁移文档,例如.一些使用router.go()现在不起作用的例子.
Edd*_*Edd 27
我不同意最好的答案 - 你可以$route毫无问题地嘲笑.
另一方面,在基础构造函数上多次安装vue-router 会导致问题.它添加$route和$router作为只读属性.这使得在将来的测试中无法覆盖它们.
使用vue-test-utils有两种方法可以实现这一点.
用mocks选项模拟vue-router
const $route = {
fullPath: 'full/path'
}
const wrapper = mount(ComponentWithRouter, {
mocks: {
$route
}
})
wrapper.vm.$route.fullPath // 'full/path'
Run Code Online (Sandbox Code Playgroud)
您还可以使用createLocalVue安全地安装Vue Router:
使用createLocalVue在测试中安全地安装vue-router
const localVue = createLocalVue()
localVue.use(VueRouter)
const routes = [
{
path: '/',
component: Component
}
]
const router = new VueRouter({
routes
})
const wrapper = mount(ComponentWithRouter, { localVue, router })
expect(wrapper.vm.$route).to.be.an('object')
Run Code Online (Sandbox Code Playgroud)
没有答案帮助我,所以我深入研究vue-test-utils文档并找到了一个可行的答案,所以你需要导入。
import { shallowMount,createLocalVue } from '@vue/test-utils';
import router from '@/router.ts';
const localVue = createLocalVue();
Run Code Online (Sandbox Code Playgroud)
我们创建了一个示例vue实例。在测试时您需要使用,shallowMount以便您可以提供vue应用程序实例和路由器。
describe('Components', () => {
it('renders a comment form', () => {
const COMMENTFORM = shallowMount(CommentForm,{
localVue,
router
});
})
})
Run Code Online (Sandbox Code Playgroud)
您可以轻松地通过路由器和浅安装,它不会给您错误。如果你想通过你使用的商店:
import { shallowMount,createLocalVue } from '@vue/test-utils';
import router from '@/router.ts';
import store from '@/store.ts';
const localVue = createLocalVue();
Run Code Online (Sandbox Code Playgroud)
然后通过商店:
describe('Components', () => {
it('renders a comment form', () => {
const COMMENTFORM = shallowMount(CommentForm,{
localVue,
router,
store
});
})
})
Run Code Online (Sandbox Code Playgroud)
此解决方案解决了以下错误:
this.$route.params.idrouter-link?
| 归档时间: |
|
| 查看次数: |
15806 次 |
| 最近记录: |