我有一个方案可以从基类中监视受保护的属性。
export class BaseClass {
protected property1: string;
}
export class InheritedClass extends BaseClass, OnInit {
ngOnInit() {
this.populateProperties();
}
populateProperties() {
this.property1 = "test";
}
}
我正在为此编写单元测试,但未返回property1
。可能是什么问题?
describe('populateProperties', () => {
it('should assign the properties values', () => {
// arrange
const spy = spyOnProperty((component as any), 'property1');
// act
component.populateProperties();
// assert
expect(spy).toBeDefined();
});
});
这是实例变量,而不是函数,因此不能被窥探。
尝试一下:
describe('populateProperties', () => {
it('should assign the properties values', () => {
// act
component.populateProperties();
// assert
expect((component as any).property1).toBeDefined();
});
});
我假设any
是必需的,因为property1
在BaseClass中受保护,但这不是最佳实践。您应该只测试组件的HTML / View,公共方法和公共属性。