2017-08-08 41 views
0

我想測試組件,我打電話$t()來翻譯我的文本和this.$route.name我需要在我的測試注入插件,否則我得到一個錯誤日誌

測試我創建了通行證,但與許多ERROR LOG

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


ERROR LOG: '[Vue warn]: Error in mounted hook: "TypeError: undefined is not an object (evaluating '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) ERROR TypeError: undefined is not an object (evaluating '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", 
} 
+0

你是如何導入VueI18n到您的測試腳本? – thanksd

+0

@感謝我在我的main.js中執行相同的操作(我更新了我的問題) – smarber

回答

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'); 
    }); 
}); 
相關問題