首页 > 解决方案 > 在ngOninit期间是否调用组件方法的角度测试?

问题描述

我的目标是创建某些方法的间谍,并检查在 ngOninit 期间是否调用了这些方法以及 pagePurpose 是否等于 Update。目前我试图设置间谍并在描述中设置组件属性,然后尝试断言是否调用了函数,但我得到:预期的间谍 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();
  });

非常感谢您的帮助!

标签: angularunit-testingjasminengoninit

解决方案


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();
});

推荐阅读