3

我是角度的新手。我正在尝试为 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 不是函数。

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

4

1 回答 1

2

试试这个

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

还要确保updateSize用大写调用模拟方法S

于 2020-07-10T13:45:54.323 回答