2017-10-05 45 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