使用私有变量进行角度单元测试

时间:2017-10-06 08:45:10

标签: angular unit-testing jasmine

我想为私有变量编写单元测试。但Jasmine不允许我使用它。有人能解释我怎么做吗?

export class TestComponent implements OnInit {
  private resolve;

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

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

1 个答案:

答案 0 :(得分:7)

 expect(component['resolve']).toEqual(false);

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

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

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

因为您正在调用this.resolve(false),这意味着它是一个功能,那么您为什么要测试它等于false

编辑:

你是说这个意思吗?

 public testPrivate() {
   this.resolve = false;
 }
相关问题