【问题标题】:Avoid vue warnings when mocking router in vue.js tests在 vue.js 测试中模拟路由器时避免 vue 警告
【发布时间】:2018-03-16 19:55:39
【问题描述】:

我正在测试一个使用 Axios 处理 HTTP 请求的 Vue.js 2 应用程序,并且我正在使用 Moxios 模拟这些请求。该测试也使用 Avoriaz。

我正在测试的页面只是呈现一个元素列表并显示一些使用<router-link>实现的按钮

问题是我在测试中收到了很多警告

ERROR LOG: '[Vue warn]: Unknown custom element: - 您是否正确注册了组件?

我要测试的页面如下所示(简化):

<template>
<div>
  <ul>
    <li v-for="myelement in myobject.myelements">
        {{myelement.id}}
    </li>
  </ul>
  <router-link :to="{name: 'myElementCreate'}">New element</router-link>
</div>
</template>
<script>
import myService from './my-service.js'

export default {
  name: 'my-list',
  data() {
    return {
      myobject: {
        myelements: []
      }
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    fetchData() {
      if (this.$route.params.id) {
        myService.get(this.$route.params.id)
          .then((response) => {
            // init data from response
          })
      }
    }
  }
}
</script>

测试看起来像这样:

import Vue from 'vue'
import moxios from 'moxios'
import {shallow} from 'avoriaz'
import MyElements from '@/my-elements'

describe('My Elements', () => {
  beforeEach(() => {
    moxios.install()
  })

  afterEach(() => {
    moxios.uninstall()
  })

  it('Renders elements list', (done) => {
    moxios.stubRequest(/.*/, {
      status: 200,
      response: existingElement
    })

    // mock route to allow fetchData() to load elements
    const component = shallow(MyElements, {
      globals: {
        $route: {params: {'id': 1}}
      }
    })

    moxios.wait(() => {
      Vue.nextTick(() => {
        try {
          const myElement = component.find('ul li')
          expect(myElement[0].text()).to.equal('6035132')
        } catch (e) {
          done(e)
        }
        done()
      })
    })
  })
})

const existingElement = {
  'id': 6035132
}

如果我添加 Vue.use(Router) 和相应的导入,警告就会消失,但我的 Moxios 模拟将不再起作用。知道如何摆脱这些警告吗?

【问题讨论】:

    标签: unit-testing vuejs2 axios avoriaz moxios


    【解决方案1】:

    问题是router-link没有注册为组件。

    如果不安装 Vue Router,router-link 组件没有注册。这意味着它不能在您的组件中使用。

    要解决这个问题,您可以注册一个存根路由器链接组件:

    // mock component
    Vue.component('router-link', {
      name: 'router-link',
      render: h => h('div')
    })
    
    const component = shallow(MyElements, {
      globals: {
        $route: {params: {'id': 1}}
      }
    })
    

    【讨论】:

    • 感谢 Edd,这正是我想要的,但我并没有想到嘲笑它。我刚刚编辑了你的答案来解决我的问题,因为你的代码没有为我运行('routerLink' 被分配了一个值,但从未使用过 + 'routerView' 没有定义)。可能只是复制+粘贴错误...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-11
    • 2020-12-23
    • 1970-01-01
    • 2017-12-24
    • 2017-04-15
    • 2015-12-23
    • 2021-12-06
    相关资源
    最近更新 更多