0

我試圖測試我的Angular 2服務,它使用Observables和ngrx存儲。我有大多數測試通過,但在我的一個測試中,我試圖嘲笑HTTP調用,我相信我做的是正確的,但是我的問題是我的代碼在「注入」語句中沒有實際執行:Karma/Jasmine測試Angular 2服務不執行內部注入代碼

@Injectable() 
export class FirmService { 
    public stateObservable: Observable<FirmState>; 

    constructor(private $http: AuthHttp, private store: Store<FirmState>) { 
    // whatever reducer is selected from the store (in line below) is what the "this.store" refers to in our functions below. 
    // it calls that specific reducer function 
    this.stateObservable = this.store.select('firmReducer'); 
} 

public getFirms(value?: string) { 
    return this.$http.get('/api/firm').map((response: Response) => { 
     this.store.dispatch({ 
      type: firmActions.GET_FIRMS, 
      payload: response.json() 
     }); 
     return; 
    }); 
    } 
} 

我對getFirms測試:

beforeEach(() => { 
    TestBed.configureTestingModule({ 
     imports: [HttpModule, AppModule], 
     providers: [ 
      { provide: XHRBackend, useClass: MockBackend }, 
      FirmService 
     ] 
    })); 


    // using these mock firms in other tests as well 
    firms = { 
     firms: [ 
      { 
       'name': 'ICBC', 'country': 'United States', 'industry': 'Financial Services', 
       'edfModels': [{ 'name': 'US FIN 4.0', 'QO': false }, { 'name': 'US FIN 4.0', 'QO': true }], 
       'lgdModels': [{ 'name': 'US FIN 4.0', 'QO': false }, { 'name': 'US FIN 4.0', 'QO': true }], 
       'modifiedOn': '1/1/2016', 'modifiedBy': 'John Doe' 
      }, 

      { 
       'name': 'CCBC', 'country': 'United States', 'industry': 'Financial Services', 
       'edfModels': [{ 'name': 'US FIN 4.0', 'QO': false }, { 'name': 'US FIN 4.0', 'QO': true }], 
       'lgdModels': [{ 'name': 'US FIN 4.0', 'QO': false }, { 'name': 'US FIN 4.0', 'QO': true }], 
       'modifiedOn': '1/1/2016', 'modifiedBy': 'John Doe', 'selected': true 
      } 
     ] 
    }; 
}); 

it('getFirms should dispatch the GET_FIRMS action', inject([FirmService, XHRBackend], (firmServiceMock, mockBackend) => { 
    const expectedAction = { 
     type: firmActions.GET_FIRMS, 
     payload: firms 
     }; 

     mockBackend.connections.subscribe((connection) => { 
      connection.mockRespond(new Response(new ResponseOptions({ 
        body: JSON.stringify(firms) 
      }); 
     })); 

     spyOn(mockStore, 'dispatch'); 

     firmServiceMock.getFirms().subscribe(() => { 
      expect(mockStore.dispatch).toHaveBeenCalled(); 
      expect(mockStore.dispatch).toHaveBeenCalledWith(expectedAction); 

     }); 
})); 

誰能告訴我什麼,我需要做的,在我的規格文件中刪除此錯誤: 類型錯誤:http.get(...)地圖(... ).toPromise不是一個函數。

它不應該在我的服務執行http調用,如果我嘲笑它?

回答

1

由於我沒有所有的依賴關係,我無法驗證這一點,但我相信你需要在它阻塞之前進行注入,就像beforeEach一樣。

+0

謝謝..看起來像我不得不把它移動到它的實際聲明..我更新了我的代碼,但現在我得到這個錯誤:「TypeError:http.get(...)。map(... ).toPromise不是一個函數「,當它到達我的firmServiceMock.getFirms()。訂閱代碼行時。我試過這個解決方案:https://stackoverflow.com/questions/39121286/angular2-typeerror-this-http-get-topromise-is-not-a-function。但是,當我添加錯誤停止,但沒有代碼運行在我的訂閱功能。我已經添加了我正在測試的服務。謝謝 – bschmitty