如何编写模拟 vue 组件中的 $route 对象的测试

编程入门 行业动态 更新时间:2024-10-25 20:23:10
本文介绍了如何编写模拟 vue 组件中的 $route 对象的测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含像 this.$route.fullPath 这样的语句的组件,我应该如何模拟 $route 对象的 fullPath 的值如果我想测试那个组件?

I have a component that contains statement like this.$route.fullPath, how should I mock value of fullPathof $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:关键词]

本文发布于:2023-03-31 10:12:10,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/801940.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:组件   对象   测试   vue   route

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!