【问题标题】:Jasmine spy on base class protected property茉莉花窥探基类受保护的财产
【发布时间】:2020-09-09 06:01:27
【问题描述】:

我有一个场景可以从基类中窥探受保护的属性。

export class BaseClass {
    protected property1: string;
}

export class InheritedClass extends BaseClass, OnInit {

   ngOnInit() {
        this.populateProperties();
   }

   populateProperties() {
       this.property1 = "test";
   } 
}

我正在尝试为此编写单元测试,但返回 property1 not found。可能是什么问题?

describe('populateProperties', () => {
    it('should assign the properties values', () => {
      // arrange
      const spy = spyOnProperty((component as any), 'property1');

      // act
      component.populateProperties();

      // assert
      expect(spy).toBeDefined();

    });
  });

【问题讨论】:

    标签: angular typescript jasmine karma-jasmine angular-unit-test


    【解决方案1】:

    它是一个实例变量,而不是一个函数,因此它不能被窥探。

    试试这个:

    describe('populateProperties', () => {
        it('should assign the properties values', () => {
          // act
          component.populateProperties();
    
          // assert
          expect((component as any).property1).toBeDefined();
        });
      });
    

    我假设 any 是必需的,因为 property1 在 BaseClass 中受到保护,但这不是最佳实践。您应该只测试组件的 HTML/View、公共方法和公共属性。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-04-19
      • 1970-01-01
      • 2020-01-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-12
      • 1970-01-01
      相关资源
      最近更新 更多