【发布时间】:2017-10-26 08:38:27
【问题描述】:
我需要能够测试我的组件(方法、计算属性、数据……)。但是,当我在单元测试中导入我的 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 属性。使用 karma 运行测试显示成功,但 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文件时必须添加声明:
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的请求
【问题讨论】:
标签: unit-testing typescript jasmine vue.js karma-runner