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

Ish*_*Ish 2 unit-testing jasmine angular

我想为私有变量编写单元测试.但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);
 });
Run Code Online (Sandbox Code Playgroud)

Mil*_*lad 10

 expect(component['resolve']).toEqual(false);
Run Code Online (Sandbox Code Playgroud)

要么

 expect((<any>component).resolve).toEqual(false);
enter code here
Run Code Online (Sandbox Code Playgroud)

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

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

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

编辑:

你是说这个意思吗?

 public testPrivate() {
   this.resolve = false;
 }
Run Code Online (Sandbox Code Playgroud)