茉莉花间谍基地 class 受保护 属性

Jasmine spy on base class protected property

我有一个方案可以从基地 class 监视受保护的 属性。

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、public 方法和 public 属性。