gpt4 book ai didi

Angular Mat对话框单元测试: This. dialogref.updatesize不是函数

转载 作者:行者123 更新时间:2023-12-05 03:51:35 25 4
gpt4 key购买 nike

我是 Angular 的新手。我正在尝试为 mat 对话框编写单元测试,但它会抛出错误。

我在ts文件中的方法:

isMobileScreen= Observable<BreakpointState>= this.breakpointObserver.observe('(max-width:600px)');

OpenDialog(){
if(index===0){
this.dialogref=this.dialog.open(MyComonent,{
maxWidth:'600px'
});

Const dialogSub= this.isMobileScreen.subscribe(result=> {
if(result.matches){
this.dialogref.updatesize('100%','100%');
}
else{
this.dialogref.updatesize('50%');
}
});

this.dialogref.afterclosed(). subscribe (results=>{
dialogSub.unsubcribe():
});
}

规范文件

       class isMobileScreen {
Value= new subject ();
isMobileScreen= this.value.asObservable();
setValue(val){ // getting error here cannot read property 'setvalue' of undefined
this.value.next(val);
}
}

// Inside describe


describe('component', ()=>{
...
Let isMobileScreen: isMobileScreen;
Const dialogRefMock={
afterClosed(){
return of(true);
},
updatesize(width?:string, height?: string){}
};
Const dialogMock={ open:()=> dialogRefMock};

// Inside before each I gave dialogMock as provider
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ MyComponent],
imports: [RouterTestingModule,MatDialogModule],
providers: [ { provide: MatDialog, useValue: dialogStub },{provide : MatDialogRef, useValue : {}, { provide: isMobileScreen, useValue: isMobileScreen }]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(MyComponent);
component = fixture.componentInstance;
fixture.detectChanges();
isMobileScreen = TestBed.get(isMobileScreen);
});
it('',async(()=>{
component.Opendialog();
isMobileScreen.setvalue(true);
fixture.detectChanges();
fixture.whenStable().then(()=>{
let spy= spyOn(component.dialogref, 'updatesize').and.callThough();
expect (spy).toHaveBeenCalled(); // getting error here this.dialogref.updatesize is not a function.

});
}));
});

我遇到了两个错误。

  1. 无法读取未定义的属性“setvalue”
  2. this.dialogref.updatesize 不是函数。

可能是我写错了mocking。请帮我解决这个错误

最佳答案

试试这个

    providers: [ { provide: MatDialog, useValue: dialogMock },
{provide : MatDialogRef, useValue : dialogRefMock}
]

还要确保被模拟的方法被称为 updateSize 并且大写 S

关于Angular Mat对话框单元测试: This. dialogref.updatesize不是函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62778810/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com