0

我正在修复/向现有应用程序添加单元测试。下面是代码遵循的模式。方法调用其他方法。单元测试使用一些模拟类。

调用fixture.detectChanges( )就是调用ngOnInit(),它调用链中的所有其余方法。我想要的只是调用一种方法,methodC()

我调用fixture.detectChanges()的原因是将新值绑定到模板。有没有办法在不调用fixture.detectChanges()的情况下这样做?

export class MyComponent implements OnInit {
  property1: any;
  property2: any

  constructor(
    private service1: Service1,
    private service2: Service2,
    ){}
   
  ngOnInit() {
    this.methodA();
  }

  methodA(){
    this.methodB();
  }
  

  methodB(){
     this.service1.doThis();
     this.service2.doThat()
         .subscribe(result => {
             this.property1 = result
             this.methodC()
      });
  }

   methodC(){
      //do something with PROPERTY1
      this.property2 = ...someValue;
   }
 }

这里的模板

 <div class="class1" *ngIf="property2?.value === 'someValue1'">
    Pending purchase 
 </div>
 <div class="class2" *ngIf="property2?.value === 'someValue2'">
    Order Submitted 
 </div>

我的单元测试

  it('should display pending purchase if amount is null or undefined', () => {
      fixture.detectChanges();    //--> THIS WILL RUN THE LIFECYCLE 
      
      component.property1 = {}    //SOME VALUE
      component.methodC().        //RUN THE LOGIC TO PRODUCE A VALUE FOR property2

      //fixture.detectChanges();  // THIS IS RUNNING EVERYTHING AND OVERRIDE NEW VALUES

      const elt = element.querySelector('.class1');
      expect(elt).not.toBeNull();
  });

感谢您的帮助。

4

1 回答 1

1

覆盖应该可以解决问题:

it('should display pending purchase if amount is null or undefined', () => {
      const originalOnInitFunc = MyComponent.prototype.ngOnInit;
      const overrideOnInitFunc = () => { };
      MyComponent.prototype.ngOnInit = overrideOnInitFunc; // override ngOnInit

      component.property1 = {};
      component.methodC();

      fixture.detectChanges();

      const elt = element.querySelector('.class1');
      MyComponent.prototype.ngOnInit = originalOnInitFunc; // revert ngOnInit

      expect(elt).not.toBeNull();
   });
于 2021-05-19T17:54:56.493 回答