簡體   English   中英

在vue.js測試中模擬路由器時避免vue警告

[英]Avoid vue warnings when mocking router in vue.js tests

我正在測試使用Axios進行HTTP請求的Vue.js 2應用程序,並使用Moxios來模擬這些請求。 該測試也使用Avoriaz。

我正在測試的頁面僅呈現元素列表並顯示一些使用<router-link>實現的按鈕

問題是我在測試中收到很多警告,這些警告的風格是

錯誤日志:'[Vue警告]:未知的自定義元素:<router-link>-您是否正確注冊了組件?

我要測試的頁面如下所示(簡化):

<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模擬不再起作用。 任何想法如何擺脫這些警告?

問題是路由器鏈接未注冊為組件。

如果您未安裝Vue路由器,則不會注冊router-link組件。 這意味着它不能在您的組件中使用。

要解決此問題,您可以注冊存根路由器鏈接組件:

// mock component
Vue.component('router-link', {
  name: 'router-link',
  render: h => h('div')
})

const component = shallow(MyElements, {
  globals: {
    $route: {params: {'id': 1}}
  }
})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM