【问题标题】:Angular how to test MatDialog functions - open and closeAngular 如何测试 MatDialog 功能 - 打开和关闭
【发布时间】:2021-12-22 07:50:11
【问题描述】:

我正在尝试测试 MatDialog 的打开和关闭功能。我正在尝试的任何东西都无法测试打开功能或关闭功能。我如何模拟并实际测试它?如果我在我的代码中这样做,我将在“关闭”函数上收到 spyOn 的此错误:“类型为“关闭”的参数不可分配给类型为“keyof MatDialog”的参数”TS:

//... imports etc.
dialogRef:MatDialogRef<DialogComponent>

constructor(public dialogService:MatDialog){}

public test(){
this.openProgressDialog();
//http request
this.closeProgressDialog();
}

public openProgressDialog(){
this.dialogRef=this.dialogService.open(DialogComponent,{
  disableClose:true,
  height:'150px',
  width:'400px'
});
}

public closeProgressDialog(){
  this.dialogRef.close();
}

spec.ts:

//... imports
describe("TestComponent",()=>{
   beforeEach(async () => {
   await TestBed.configureTestingModule({
   imports:[appModule,MatDialogModule],
   providers:[DialogComponent],
}).compileComponents();
 
  fixture=TestBed.createComponent(TestComponent);
  component=fixture.componentInstance;
  fixture.detectChanges();
})

test("should test", ()=>{
  spyOn(component.dialogService,'open').and.call.Through(); // the problem is at this two lines
  spyOn(component.dialogService,'close').and.call.Through(); 
  component.test();
  //expect ... (just for example)
})

【问题讨论】:

    标签: angular typescript unit-testing jestjs jasmine


    【解决方案1】:

    我相信你有一个额外的点

    test("should test", ()=>{
      spyOn(component.dialogService,'open').and.callThrough(); 
      spyOn(component.dialogService,'close').and.callThrough();
     
      component.test();
      
      expect(component.dialogService.open).toHaveBeenCalled();
      expect(component.dialogService.close).toHaveBeenCalled();
    })
    

    【讨论】:

      猜你喜欢
      • 2021-12-17
      • 2020-10-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多