2016-04-28 74 views
0

我正在爲Vue應用程序編寫一些單元測試。當我嘗試測試DOM內容時,一切都很好,但我無法訪問我的組件的數據。實際上,如果我的組件$data屬性沒有數據,它會打印一個空對象,沒有最初定義的數據或任何其他數據。根本不值一提。Vue.js - 在karma/phantomjs測試中丟失的數據

下面是一些代碼

一些VUE組件

<template> 
    <form @submit.prevent="saveAccount"> 
     <label for="accountType">Tipo de cuenta</label> 
     <select class="form-control" id="accountType" v-model="newAccount.type"> 
      <option v-for="type in accountTypes" v-bind:value="type.value"> 
      {{type.label}} 
      </option> 
     </select> 
    </form> 
</template> 
<script> 
export default { 
    data() { 
    return { 
     accountTypes: [ 
     {value: '1', label: 'Activo'}, 
     {value: '2', label: 'Pasivo'}, 
     {value: '3', label: 'Patrimonio'}, 
     {value: '4', label: 'INTO'} 
     ] 
    } 
    } 
} 
</script> 

我的測試

beforeAll(() => { 
    vm = new Vue({ 
     template: '<div><account></account></div>', 
     components: { account } 
    }).$mount() 
    }) 

    afterAll(() => { 
    vm.$destroy(true) 
    }) 

    it('account type',() => { 
    // this pass 
    expect(vm.$el.querySelectorAll('#accountType option').length).toBe(4) 
    const options = vm.$el.querySelectorAll('#accountType option') 
    // here accountTypes is undefined 
    const accountValues = vm.accountTypes.map(type => { 
     return type.value 
    }) 
    options.forEach(option => { 
     expect(accountValues.indexOf(option.value)).not.toBe(-1) 
    }) 
    }) 

被省略了一些代碼。那麼,爲什麼我的組件數據是空的,但同時在DOM中正確呈現?

回答

1

經過一番嘗試和錯誤,我找到了答案,現在很明顯。問題是,我在錯誤的地方搜索數據。我喜歡這個

vm = new Vue({ 
    template: '<div><account></account></div>', 
    components: { account } 
}).$mount() 

定義的vm對象是Vue的實例只有一個組件,模板選項,數據我正在尋找是在孩子該實例的。所以,我必須用這種方式來訪問數據

const accountInstance = vm.$children[0] 

這樣做,因爲測試我定義了一個容易識別的單個孩子。我也嘗試過在使用const accountInstance = new account()之前嘗試過但因爲vue組件不是構造函數而引發錯誤