2017-05-25 97 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) 
    }) 
})