簡體   English   中英

在業力單元測試中未定義VueRouter

[英]VueRouter is undefined in karma unit tests

在新的Vue.js項目上運行的測試期間,我收到警告。 無論組件在模板中將<router-link>用作<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');
  });
});

看來您的路由可能未在測試環境中的任何地方建立。 如果您使用的是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')
  })
  ...
})

暫無
暫無

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

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