typescript 使用MatDialog进行Angular 单元测试-错误::< spyOn>open已被监视

afdcj2ne  于 2023-03-04  发布在  TypeScript
关注(0)|答案(1)|浏览(164)

我创建了一个html文件与按钮。onClickEvent轮询后出现,下一步,点击按钮后"提交"对话框窗口关闭,我想调用下一个方法。
TS.file:

openDialogWindow() {
const dialogRef = this.dialogWindow.open(PollComponent, {
  width: '400px',
  height: '400px',
  data: getData()
});

dialogRef.afterClosed().subscribe(result => {
  if (result.status == 'VALID') {
    answerForm = result;
    this.callNextFunction();
  }
});

}
然后我在spec. ts文件中创建了单元测试:

it('should call dialogwindow and after submit call methods', () => {
service.callNextFunction.and.returnValue(of({value: 0}));

const result = new FormGroup({}, )
result.setValidators(null);
spyOn(component.dialogWindow, 'open')
  .and
  .returnValue({
    afterClosed: () => of(true)
  } as MatDialogRef<typeof component>);
  
fixture.detectChanges();
expect(component.dialogWindow.afterAllClosed).toContain(result);
expect(service.callNextFunction).toHaveBeenCalled();
expect(component.otherForm.recommendedValue.control.value).toEqual('123');

});
但是当我测试它的时候,我得到了错误:

Error: <spyOn> : open has already been spied upon
Usage: spyOn(<object>, <methodName>)

是否由创建引起:

matDialogSpy = createSpyObj<MatDialog>('MatDialog', ['open']);

在beforeEach中?我在其他单元测试中使用matDialogSpy检查单击按钮后对话框窗口是否打开:

it('should open dialog when button has been clicked', fakeAsync(() => {
clickOnSlsButtonByLabel('Open dialog', fixture);

expect(matDialogSpy.open).toHaveBeenCalledTimes(1);
expect(matDialogSpy.open).toHaveBeenCalledWith(
  PollComponent,
  {
    width: '400px',
    height: '400px',
    data: data...
  }
);

}));

blmhpbnm

blmhpbnm1#

异常是自我解释的--它已经是间谍了,就用它吧
请记住,您应该将component.dialogWindow替换为您在测试中提供的MatDialog

component.dialogWindow.open //maybe matDialogSpy.open??
  .and
  .returnValue({
    afterClosed: () => of(true)
  } as MatDialogRef<typeof component>);

相关问题