2017-05-25 118 views
1

我需要能夠測試我的組件(方法,計算屬性,數據...)。然而,當導入我VUE部件在我的單元測試:單元測試打字稿vue組件

import Pagination from 'src/components/shared/pagination.vue' 
import { newComponent } from '../component-factory' 

describe('pagination.vue',() => { 
    const propsData = { 
     metadata: { 
      page: 2, 
      records: 155, 
      total: 11, 
     }, 
     perPage: 15, 
    } 

    it('should have correct number of records',() => { 
     const ctor = Vue.extend(Pagination) 
     const vm = new ctor({propsData}).$mount() 
     expect(vm.firstRecord).toBe(16) 
     expect(vm.lastRecord).toBe(30) 
    }) 
... 

vmVue類型的,並且因此不具有firstRecord/lastRecord性質。運行與因果報應的測試表明取得了成功,但打字稿編譯器吐出的錯誤:

ERROR in ./tests/shared/pagination.spec.ts 
(16,19): error TS2339: Property 'firstRecord' does not exist on type 'Vue'. 

ERROR in ./tests/shared/pagination.spec.ts 
(17,19): error TS2339: Property 'lastRecord' does not exist on type 'Vue'. 

我試過鑄造:

... 
     const vm = new ctor({propsData}).$mount() as Pagination 
... 

但是,這導致在VSCode警告:

[ts] Cannot find name 'Pagination'. 

並且具有將vm作爲any類型的效果,這是完全適得其反的。

我覺得這一切都源自一個事實,即使用.vue文件時必須添加的聲明莖:

declare module '*.vue' { 
    import Vue from 'vue' 
    export default typeof Vue 
} 

它清楚地規定所有.vue文件到Vue的類型,這是不準確一個謊言,但也沒有幫助...任何建議?我究竟做錯了什麼?

爲了將來的參考,我試圖使用vuetype爲每個.vue文件生成.d.ts文件,但遇到了this issue。另外,there is a request使.vue成爲打字稿生態系統中的頭等公民,從而消除此問題。而且,我只是增加了vue language service extension

回答

1

直到Vue公司2.5的請求,建議他們打字稿文檔頁面導出擴展Vue如果你不打算使用vue-class-component的接口。您可以導出此接口以在您的測試中使用,以投射您的組件實例。該建議已從文檔中刪除,但我無法弄清楚如何將測試更改爲不需要該界面。

它看起來像vuetype可以爲你生成這些接口,但我剛剛手動創建它們。

這裏是一個大大簡化的例子,但您可以定義界面中的任何東西,你會在vm引用,即數據,道具,方法:

// NOTE: Make sure your interface extends `Vue`! 
export interface PaginationComponent extends Vue { 
    firstRecord: number, 
    lastRecord: number 
} 

export default { 
    name: 'Pagination', 
    data: function() { 
    return { 
     firstRecord: 16, 
     lastRecord: 30, 
    } 
    } 
} 

爲您的測試,你可以投中的組件實例到您導出的接口類型:

import Pagination, {PaginationComponent} from 'src/components/shared/pagination.vue' 

describe('pagination',() => { 
    it('should know about component data fields',() => { 
    const ctor = Vue.extend(Pagination) 
    const vm : PaginationComponent = new ctor().$mount() 
    expect(vm.firstRecord).toBe(16) 
    expect(vm.lastRecord).toBe(30) 
    }) 
})