角度测试是否在ngOninit期间调用了组件方法?

问题描述

我的目标是创建某些方法的间谍,并检查在ngOninit期间是否调用了这些方法以及pagePurpose是否等于Update。目前,我正在尝试设置间谍并在describe中设置component属性,然后尝试断言是否调用函数,但我得到了:预期的间谍createLineReviewRequest已被调用。我觉得我是在创建间谍,但没有正确使用它们。我还需要使用Highlight方法来执行此操作,请注意,就我而言,我不在乎通过了什么方法

我的组件如下:

export class ReportsModalLineReviewComponent implements OnInit {
  
  pagePurpose: string;
  canContinue: boolean ;

  constructor() { }

  ngOnInit() {
   
    if (this.pagePurpose === "Update" ) {
      this.highlight(this.dialogData.oldReport.lineReviewRequest.lineReviewFile.fileId)
      this.createLineReviewRequest(this.dialogData.oldReport.lineReviewRequest.lineReviewFile);
      this.canContinue = true;
    }
  }

Mt测试如下:

beforeEach(() => {
    fixture = Testbed.createComponent(ReportsModalLineReviewComponent);
    component = fixture.componentInstance;

    component.pagePurpose = "Update";
    spyOn(component,'createLineReviewRequest');

    fixture.detectChanges();
 });

fit('should check if Update',() => {
    
    expect(component.createLineReviewRequest).toHaveBeenCalled();
  });

非常感谢您的帮助!

解决方法

onInit需要手动调用

我建议遵循约定进行单元测试。 给予->何时->然后

let component: ReportsModalLineReviewComponent;
let fixture: ComponentFixture<ReportsModalLineReviewComponent>;

beforeEach(async(() => {
  TestBed.configureTestingModule({
    imports: [CommonModule],declarations: [ReportsModalLineReviewComponent]
  }).compileComponents();
}));

beforeEach(() => {
    fixture = TestBed.createComponent(ReportsModalLineReviewComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
 });

fit('should check if Update',() => {
    // GIVEN
    component.pagePurpose = "Update";
    spyOn(component,'createLineReviewRequest');

    // WHEN
    component.ngOnInit()

    // THEN
    expect(component.createLineReviewRequest).toHaveBeenCalled();
});