【问题标题】:I need to inject plugins in my tests otherwise I get an ERROR LOG我需要在我的测试中注入插件,否则我会得到一个错误日志
【发布时间】:2018-01-16 01:16:40
【问题描述】:

我想测试一个 组件,我调用 $t() 来翻译我的文本和this.$route.name

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

ERROR LOG: '[Vue warn]: Error in render function: “TypeError: undefined is not a function (evalating '_vm.$t('contact')')”


ERROR LOG: '[Vue warn]: 挂载钩子错误:“TypeError: undefined is not an object (evalating 'this.$route.name')”

这是我的 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 is not an object (evalating '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",
}

【问题讨论】:

  • 你是如何将 VueI18n 导入你的测试脚本的?
  • @thanksd 与我在 main.js 中的操作方式相同(我更新了我的问题)

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


【解决方案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');
    });
});

【讨论】:

    猜你喜欢
    • 2019-07-25
    • 2013-11-21
    • 1970-01-01
    • 2021-10-01
    • 1970-01-01
    • 2019-05-09
    • 2011-05-15
    • 2022-11-30
    • 1970-01-01
    相关资源
    最近更新 更多