【问题标题】:Angular unit test with private variable带有私有变量的角度单元测试
【发布时间】:2017-10-06 08:45:09
【问题描述】:

我想为私有变量编写单元测试。但是茉莉花不允许我使用它。有人可以解释一下怎么做吗?

export class TestComponent implements OnInit {
  private resolve;

  public testPrivate() {
    this.resolve(false);
  }
}

 it(
      'should test private variable', () => {
        component.testPrivate();
        expect(component.resolve).toEqual(false);
 });

【问题讨论】:

    标签: angular unit-testing jasmine


    【解决方案1】:
     expect(component['resolve']).toEqual(false);
    

     expect((<any>component).resolve).toEqual(false);
    enter code here
    

    但是,从技术上讲,您不应该仅仅因为它是类的private 成员而测试私有变量,并且只能在类本身内访问它,如果您真的想测试它,则必须将其公开或为它创建一个gettersetter,它是公开的。

    顺便说一句,你的测试对我来说没有多大意义,除非你没有在这里写完整的测试。

    因为你调用this.resolve(false),意味着它是一个函数,那你为什么要测试它等于false

    编辑:

    你是说这个吗:?

     public testPrivate() {
       this.resolve = false;
     }
    

    【讨论】:

    • TypeError: this.resolve 不是函数。尝试第一种方法时出现此错误。
    • 你怎么期待这个:private resolve; 成为一个你可以调用的函数?
    • 不错的解决方案.. 兄弟
    • 也可以这样expect((component as any).resolve).toEqual(false);
    猜你喜欢
    • 2016-08-05
    • 1970-01-01
    • 2019-12-19
    • 2018-06-27
    • 1970-01-01
    • 1970-01-01
    • 2023-04-10
    • 2018-06-17
    • 2021-11-12
    相关资源
    最近更新 更多