2017-05-25 1 views
1

私のコンポーネント(メソッド、計算されたプロパティ、データ、...)をテストできるようにする必要があります。私はユニットテストの私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) 
    }) 
... 

vmをタイプVueのものであり、したがって、firstRecord/lastRecord性質を持っていません。カルマでテストを実行すると、成功を示しているが、typescriptですコンパイラはエラーを吐く:

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へのすべての.vueファイルの種類を設定します

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

私はこのすべてが.vueファイルを使用しているときに宣言を追加する必要があるという事実に由来だと思いますうそだけど、どちらにも役立たない...どんな提案?私は間違って何をしていますか?

今後参考になるように、.vueファイルごとに.d.ts個のファイルを生成するvuetypeを使用しようとしましたが、this issueに及んでいました。また、there is a requestは、.vueをタイプコピーエコシステムの第一級市民にして、この問題を解消します。 vue language service extension

答えて

1

Vue 2.5まで、vue-class-componentを使用しない場合は、TypeScriptのドキュメントページで、Vueの拡張インターフェイスをエクスポートすることをお勧めします。このインタフェースをエクスポートして、テストで使用し、コンポーネントインスタンスをキャストすることができます。この勧告はドキュメントから削除されていますが、インタフェースを必要としないようにテストを変更する方法を見つけることができませんでした。

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) 
    }) 
}) 
関連する問題