2017-08-04 94 views
0

我有一個單元測試,我解決不了問題。 這裏是我的測試:角單元測試spyOn沒有檢測到我的電話

fit('should call the alert service in case something went wrong getting the list of files', async(() => { 
    spyOn(this.component.alert, 'error'); 
    this.component.onInputChange('error'); 
    this.fixture.whenStable().then((() => { 
     expect(this.component.alert.error).toHaveBeenCalledWith('an error occured'); 
    })); 
})); 

這裏是我的測試組件的一部分:

private onInputChange (search: string) { 
    const that = this; 
    this.translateFileService.getVideoFiles(search) 
     .then(files => (files.length) ? this.files = files : '') 
     .catch(this.alert.error.bind(that)); 
} 

出於測試目的,translateFileService被嘲笑像這樣:

class TranslateFileServiceMock { 

    getVideoFiles (search: string): Promise<IcoFile[]> { 
     const fileList = [ 
      IcoFile.fromJSON({id: '0', label: 'test0', creationTime: '2017-07-01'}), 
      IcoFile.fromJSON({id: '1', label: 'test1', creationTime: '2017-07-02'}), 
      IcoFile.fromJSON({id: '2', label: 'test2', creationTime: '2017-07-03'}), 
     ]; 

     return new Promise<IcoFile[]>((resolve, reject) => { 
      if (search === 'error') return reject('an error occured'); 
      return resolve(fileList.filter(f => f.label.includes(search))); 
     }); 
    } 

} 

onInputChange方法調用由組件中的警報屬性表示的警報服務。 警報服務沒有被嘲笑,它是真正的服務。調用它的錯誤方法實際上是我已經驗證過的。但是我的測試總是失敗:間諜沒有檢測到我的電話。

我總是有以下錯誤:

Expected spy error to have been called with [ 'an error occured' ] but it was never called. 

我不知道該怎麼辦。我嘗試了我所知道的一切。 起初我以爲我的電話沒有被正確地檢測到,因爲我在嘲笑我的警報服務,但即使是真正的服務也無法正常工作。

我希望你能幫忙,先謝謝了!

+0

您可以添加更多的代碼? – yurzui

+0

事,爲什麼你使用'this'在'this.component','this.fixture'告訴我,如果你需要更多的東西:) – Orodan

+0

? – yurzui

回答

1

似乎this.fixture.whenStable().then之前catch處理程序執行。我會用fakeAsynctick

fit('should call ...', fakeAsync(() => { 
    spyOn(component.alert, 'error'); 
    component.onInputChange('error'); 
    tick(); 
    expect(component.alert.error).toHaveBeenCalledWith('an error occured'); 
})); 

Plunker Example

+0

非常感謝您的解決方案!你有任何理由爲什麼「this.fixture.whenStable()。then」在catch處理程序之前執行?我雖然「whenstable」方法的目標是在執行某些代碼之前等待任何異步任務完成。 – Orodan

+0

我也這麼認爲。但是如果我們更深入地研究它,我們可以注意到'tick()'正在運行'flushMicrotasks'。它模擬了時間的異步流逝。雖然whenStable檢查'isStable'狀態'this._isStable &&!this.ngZone.hasPendingMacrotasks'但在測試期間出現的isStable狀態沒有改變,因爲''ngZone.onUnstable事件不會被調用。在角測試工作始終是一招:) – yurzui

+0

事實上,它看起來棘手現在還似乎頗爲奇怪的是,當返回一個承諾,一個函數被調用的onUnstable事件永遠不會觸發。無論如何,感謝您的解釋:) – Orodan