Reputation: 1218
I am trying to test my Angular 2 service, which uses Observables and the ngrx Store. I have most tests passing but in one of my tests I am trying to mock the HTTP call, which I believe I am doing correctly but my issue is that none of my code in the "inject" statement is actually executing:
@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;
});
}
}
My Test for 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);
});
}));
Can anyone tell me what I need to do to remove this error in my spec file: TypeError: http.get(...).map(...).toPromise is not a function.
It shouldn't be executing that http call in my service should it if I'm mocking it??
Upvotes: 0
Views: 368
Reputation: 4227
Since I don't have all of the dependencies, I can't verify this, but I believe you need to do the inject before the it block, as in a beforeEach.
Upvotes: 1