2017-08-03 42 views
1

我正在嘗試在單元測試之一中打開和關閉角度材質2對話框。開頭看起來很好,但我窺探了一個應該在關閉之後調用的函數,它從來沒有被調用過,我認爲這是因爲對話框沒有按照我想要的那樣關閉。Angular2 - 在單元測試中打開和關閉mdDialog

我的代碼,我想測試:

openDialog() { 
    this.dialogRef = this.dialog.open(ConfirmationDialogComponent, { 
     height: '210px', 
     width: '335px', 
     disableClose: true 
    }); 
    this.dialogRef.componentInstance.title = 'Delete Selected Intents?'; 
    this.dialogRef.componentInstance.content = 'All corresponding data will be deleted'; 
    this.dialogRef.componentInstance.option1 = 'Cancel'; 
    this.dialogRef.componentInstance.option2 = 'Delete'; 

    this.dialogRef.afterClosed().subscribe(result => { 
     this.afterDialogClose(result); 
    }); 
    } 

我的測試,到目前爲止(這是失敗的afterDialogClose不叫如預期):

it('should call afterDialogClose when the dialog closing event triggered', fakeAsync(() => { 
    spyOn(component, 'afterDialogClose'); 
    component.openDialog(); 
    fixture.detectChanges(); 
    tick(); 
    component.dialog.closeAll(); 
    fixture.detectChanges(); 
    tick(); 
    expect(component.afterDialogClose).toHaveBeenCalled(); 
    })); 

誰能告訴我我是什麼做錯了,我如何強制我的對話框關閉並調用afterDialogClose()函數?謝謝!

+0

你會得到哪個錯誤? – yurzui

+0

@yurzui「在DialogClose被調用後,預期的間諜」 – threxx

+0

'2個計時器仍在隊列中。'? – yurzui

回答

0

我認爲主要誤差是

1計時器(S)STIL在隊列中。

又見

爲了解決它,我們可以使用jasmine.done代替async/fakeAsync

it('should call afterDialogClose when the dialog closing event triggered', (done) => { 
    spyOn(component, 'afterDialogClose'); 
    component.openDialog(); 
    fixture.detectChanges(); 
    fixture.whenStable().then(() => { 
    component.dialog.closeAll(); 
    fixture.detectChanges(); 
    fixture.whenStable().then(() => { 
     expect(component.afterDialogClose).toHaveBeenCalled(); 
     done(); 
    }); 
    }); 
}); 

Plunker Example

+0

修復了隊列錯誤的權利。但仍然,afterDialogClose函數仍然沒有按預期方式調用,這意味着對話框沒有關閉。 – threxx

+0

您可以在我的plunker中重現它嗎? – yurzui