Angular 如何在不调用fixture.detectChanges()的情况下绑定模板?

Angular 如何在不调用fixture.detectChanges()的情况下绑定模板?,angular,karma-jasmine,angular-lifecycle-hooks,Angular,Karma Jasmine,Angular Lifecycle Hooks,我正在修复/向现有应用程序添加单元测试。下面是代码遵循的模式。方法调用其他方法。单元测试使用一些模拟类 调用fixture.detectChanges()就是调用ngOnInit(),它调用链中的所有其余方法。我只想调用一个方法,methodC() 我调用fixture.detectChanges()的原因是将新值绑定到模板。有没有一种方法可以不调用fixture.detectChanges() export class MyComponent implements OnInit { pro

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

调用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('如果金额为空或未定义,则应显示待定购买',()=>{
const originalOnInitFunc=MyComponent.prototype.ngOnInit;
常量overrideOnInitFunc=()=>{};
MyComponent.prototype.ngOnInit=overrideOnInitFunc;//override ngOnInit
component.property1={};
component.methodC();
fixture.detectChanges();
常量elt=element.querySelector('.class1');
MyComponent.prototype.ngOnInit=originalOnInitFunc;//还原ngOnInit
expect(elt.not.toBeNull();
});

我发现错误
MyComponent不包含“prototype”
。当我在
ngOnInit()
中放置断点时,旧的实现仍在执行中。
  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();
  });