首页 > 解决方案 > 被调用但未在角度测试中显示的功能

问题描述

我有这个代码。

export class MyComponent implements OnInit {

   ngOnInit() {
      // some code 
      this.method1(); // It comes up to here.
   }

   method1() {
       console.log('method1'); // It is not showing this.
       // Other method calls
   }
}

我的规格文件是:

  it('should call method1', fakeAsync(() => {
    const element = fixture.debugElement.nativeElement;
    spyOn(comp, 'method1');


    fixture.detectChanges();
    // some code 
    fixture.detectChanges();


    fixture.whenStable().then(async() => {
       expect(comp.method1).toHaveBeenCalled();  // this works
    });
  }));

这里有什么问题?

标签: angularunit-testingjasmine

解决方案


当您监视一个方法时,您正在用假的方法替换原始方法,这就是没有调用 method1 的原因

如果你想监视一个方法而不替换它,你必须使用 callThrough:

spyOn(comp, 'method').and.callThrough()


推荐阅读