VUERouter在业力单元测试中未定义

时间:2017-12-14 16:51:24

标签: javascript unit-testing vue.js vuejs2 vue-router

我在新的Vue.js项目上运行的测试期间收到警告。组件在模板中将路由器用作<router-link>或以编程方式this.$router.push('/');

的任何位置

测试正在通过,但记录了这些警告:

ERROR LOG: '[Vue warn]: Error in render: "TypeError: Cannot read property 'resolve' of undefined"

found in

---> <RouterLink>
   <Root>'

我正在使用Vue2,该项目基于cli工具生成的webpack项目。

我的单元测试index.js:

import Vue from 'vue';
import VueNativeSock from 'vue-native-websocket';
import Router from 'vue-router';

Vue.use(Router);
Vue.use(VueNativeSock, process.env.WEBSOCKET_ADDR, { format: 'json', reconnection: true });
Vue.config.productionTip = false;

const testsContext = require.context('./specs', true, /\.spec$/);
testsContext.keys().forEach(testsContext);

const srcContext = require.context('../../src', true, /^\.\/(?!main(\.js)?$)/);
srcContext.keys().forEach(srcContext);

我的main.js:

import Vue from 'vue';
import VueNativeSock from 'vue-native-websocket';
import VueHead from 'vue-head';
import App from './App';
import router from './router';

Vue.config.productionTip = process.env.NODE_ENV === 'production';
Vue.use(VueNativeSock, process.env.WEBSOCKET_ADDR, { format: 'json', reconnection: true });
Vue.use(VueHead);

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  template: '<App/>',
  components: { App },
  head: {
    link: [
      { rel: 'icon', href: '/static/favicon-32x32.png', sizes: '32x32', type: 'image/png' },
    ],
  },
});

任何想法,我都缺少让这些警告消失?

基本测试可能如下所示:

import Vue from 'vue';
import ViewDTCs from '@/components/ViewDTCs';

describe('ViewDTCs.vue', () => {
  const Constructor = Vue.extend(ViewDTCs);
  const vm = new Constructor().$mount();
  ViewDTCs.$socket = new WebSocket(process.env.WEBSOCKET_ADDR);
  it('has a created hook', () => {
    expect(typeof ViewDTCs.created).to.equal('function');
  });
  it('should render page', () => {
    expect(vm.$el.textContent).to.contain('Retrieving DTCs');
  });
});

1 个答案:

答案 0 :(得分:2)

您的路线可能无法在测试环境中的任何位置进行设置。如果您正在使用Karma和AvoriazVue Test Utils,我已经能够测试包含以下路线的组件:

import { mount } from 'vue-test-utils'
import router from 'src/router' // path to your router
import MyComponent from 'src/components/MyComponent'

describe('MyComponent.vue', () => {
  let wrapper

  beforeEach(() => {
    wrapper = mount(MyComponent, {
      router: router
    })
  })

  it('has a created hook', () => {
    expect(typeof wrapper.created).to.equal('function')
  })
  ...
})