2017-10-05 47 views
1

我正在測試使用Axios進行HTTP請求的Vue.js 2應用程序,我正在用Moxios模擬這些請求。該測試也使用Avoriaz。在vue.js測試中模擬路由器時避免vue警告

我只是測試頁面呈現的元素的列表,並顯示一些按鈕,其使用<router-link>

問題實行的是我在

風格得到了很多警告的在我的測試

錯誤日誌:'[Vue warn]:未知的自定義元素:< 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模擬不再工作了。任何想法如何擺脫這些警告?

回答

1

問題是router-link沒有註冊爲組件。

如果您未安裝Vue路由器,則路由器鏈路組件未註冊。這意味着它不能用於你的組件。

爲了解決這個問題,你可以註冊一個Stub路由器鏈路組成:

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

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

感謝埃德,這正是我一直在尋找,但嘲笑它並沒有來到我的腦海。我剛編輯你的答案來解決我的問題,因爲你的代碼沒有爲我運行('routerLink'被分配了一個值,但從未使用+'routerView'未定義)。可能只是一個複製+粘貼錯誤... – GreenTurtle