我需要在我的测试中注入插件,否则我会得到一个错误日志

时间:2017-08-08 12:48:27

标签: javascript unit-testing vue.js mocha karma-runner

我想测试一个组件,我在其中呼叫 $t()来翻译我的文本和this.$route.name

我创建的测试通过但有许多ERROR LOG

  

错误日志:' [Vue警告]:渲染功能出错:" TypeError:undefined不是一个函数(评估' _vm。$ t(' contact' )')"

  

错误日志:' [Vue警告]:挂钩错误:" TypeError:undefined不是对象(评估' this。$ route.name')&#34 ;

这是我的main.js

import Vue from 'vue';
import VueI18n from 'vue-i18n'

import router from './router';

import messages from './messages';

Vue.use(VueI18n);

const i18n = new VueI18n({
    fallbackLocale: 'fr',
    locale: 'fr',
    messages,
});

Vue.config.productionTip = false

let vm = new Vue({
    el: '#app',

    i18n,

    router,
});

// Once page is reloaded
i18n.locale = vm.$route.params.locale;

这是我的测试: MyComponent.spec.js

describe('MyComponent', () => {
 // other tests on the object MyComponent (not its instance)

 // Mount an instance and inspect the render output
    it('renders the correct message', () => {
        const Ctor = Vue.extend(MyComponent);
        const vm = new Ctor().$mount();
    });
});

当我尝试注入i18n时:

  import VueI18n from 'vue-i18n'

  const vm = new Ctor(new VueI18n({fallbackLocale: 'fr', locale: 'fr', messages,})).$mount();

我收到此错误

  

PhantomJS 2.1.1(Linux 0.0.0)错误     TypeError:undefined不是对象(评估' Vue.config')

的package.json

"dependencies": {
    ...
    "vue": "^2.3.3",
    "vue-i18n": "^7.1.1",
    "vue-router": "^2.6.0"
},
"devDependencies": {
    ....,
    "chai": "^3.5.0",
    "karma": "^1.4.1",
    "karma-coverage": "^1.1.1",
    "karma-mocha": "^1.3.0",
    "karma-phantomjs-launcher": "^1.0.2",
    "karma-phantomjs-shim": "^1.4.0",
    "karma-sinon-chai": "^1.3.1",
    "karma-sourcemap-loader": "^0.3.7",
    "karma-spec-reporter": "0.0.31",
    "karma-webpack": "^2.0.2",
    "sinon": "^2.1.0",
    "sinon-chai": "^2.8.0",
    "phantomjs-prebuilt": "^2.1.14",
    "mocha": "^3.2.0",
}

1 个答案:

答案 0 :(得分:1)

我使用来修复我的问题,通过mount方法,我可以注入组件依赖项。

<强> MyComponent.spec.js

import Vue from 'vue';
import VueI18n from 'vue-i18n';
import { mount } from 'avoriaz';

import MyComponent from '@/components/my_component/MyComponent.js';

Vue.use(VueI18n);

describe('MyComponent', () => {
    const i18n = new VueI18n({
        locale: 'fr',
        messages,
    });
    const $route = { name: 'toto' };

    const wrapper = mount(MyComponent, {
        i18n,
    });

    it('renders the correct message', () => {
        expect(wrapper.text()).to.contains('CONTACT');
    });
});