【发布时间】:2021-07-11 19:55:42
【问题描述】:
假设我有一个像下面这样的课程,
Class MyClass{
protected id: number;
protected name: string;
protected x:...
protected y:...
// it has many properties, assume 100 other properties
setId(id:string){
this.id = id;
}
getId(){
return this.id;
}
// get/set is applicable to all properties
}
那么,
我有一些课
class SomeClass extends MyClass{
dimension: number;
// assume it has its own definition and implementation
}
.ts 文件中的某处,我正在使用类似的函数
calculation(myClassObject: SomeClass){
...
...
}
我想对 calculation 函数进行单元测试所以我显然想模拟 SomeClass 但我不模拟它而是直接使用该类本身。
let someClass:SomeClass = new SomeClass();
someClass.dimension = 12;
在我的 .spec.ts 文件中的某处,
component.calculation(someClass); // someClass is not compitable.
由于 SomeClass 扩展了 MyClass 进一步有 100 个字段,它会引发错误,例如属性丢失。我明白为什么,但问题是我无法定义所有这 100 个字段。有没有最简单的处理方法。
或
如何模拟SomeClass?
【问题讨论】:
-
你可以直接重写一些方法,这样它们的行为就会被模拟,并且不会抛出错误。
jasmine.spyOn(someClass, 'someMethod').and.callFake(() => 123)
标签: angular unit-testing jasmine karma-jasmine