unit-testing - 如何编写在Vue组件中模拟$ route对象的测试

标签 unit-testing sinon vue-component vuejs2 vue-loader

我有一个包含类似于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()
    })
  })
})

注意事项:
  • 我正在使用vue的仅运行时版本,因此使用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/

    相关文章:

    ios - 无法从我的项目中分配任何内容 - 静态库(使用 XCTests)

    php - 创建可单元测试的 API 客户端

    javascript - sinon stub.restore 和 stub.reset 有什么区别

    javascript - 控制台记录 sinon.spy() 显示 [Function] 而不是 spy 的内容

    vue.js - VueJS - 如何在单选按钮选择上显示不同的 div

    unit-testing - 将常量添加到 PHPUnit 中的模拟

    c# - 继承自 System.Timers.ElapsedEventArgs 使单元测试更容易

    reactjs - 使用 setInterval 测试 React 组件方法

    vue-component - 如何在 Vuetify 中为 AppBar 添加 Logo ?

    vue.js - 带占位符的 VueJs 异步模板/组件