如何为 ViewChild 编写测试用例

时间:2021-02-04 06:47:57

标签: angular unit-testing karma-jasmine

谁能帮帮我?如何为 ViewChild 编写单元测试?

我尝试了几种方法,但仍然无法覆盖 viewChild。

app.ts

export class CustomerLeadDetailsComponent {
@ViewChild('ctosStatusDetails', { static: true }) ctosStatusDetails: TemplateRef<any>;

  onCtosCheck() {
    const dialogRef = this.dialog.open(DynamicPopupComponent, {
      disableClose: true,
      data: {
        title: 'Confirm your request',
        description: 'You are about to retrieve a new CTOS report.',
        buttons: [
          {
            title: 'Cancel',
            type: 'tertiary',
            onClick: () => dialogRef.close()
          },
          {
            title: 'Proceed',
            type: 'primary',
            onClick: () => null
          }
        ],
        template: this.ctosStatusDetails,
        shouldDialogActionClosePopup: false
      }
    });
  }
}

app.spec.ts

  let dialogSpy: jasmine.Spy;
  const dialogSpyObj = jasmine.createSpyObj({ afterClosed: of({}), close: null });

  it('should open modal to check CTOS status', () => {
    dialogSpy = spyOn(TestBed.get(MatDialog), 'open').and.returnValue(dialogSpyObj);
    component.onCtosCheck();
    expect(dialogSpy).toHaveBeenCalled();
  });

0 个答案:

没有答案