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

2024-01-16

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

export class TestComponent implements OnInit {
  private resolve;

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

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

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

or

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

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

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

因为你打电话来this.resolve(false),这意味着它是一个函数,那么为什么要测试它等于false ?

EDIT :

您的意思是:?

 public testPrivate() {
   this.resolve = false;
 }
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用私有变量进行角度单元测试 的相关文章