stijn26 stijn26 - 10 days ago 5
HTTP Question

How to use MockBackend in Angular2

I have this service I need to test:

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';

@Injectable()
export class LoginService {

private baseUrl: string = 'http://localhost:4000/';

constructor (private http: Http) {}

public getBaseUrl() {
return this.baseUrl;
}

getLogin() {
return this.http.get(this.baseUrl + 'api/auth/octopus')
.map(res => res.json().redirect);
}
}


To test the getLogin() function I have this code:

import {
async,
describe,
it,
expect,
beforeEach,
addProviders,
inject
} from '@angular/core/testing';
import { provide} from '@angular/core';
import { LoginService } from './login.service';
import {
Http,
BaseRequestOptions,
} from '@angular/http';
import {MockBackend} from '@angular/http/testing';


describe('Service: LoginService', () => {

beforeEach(() => addProviders([
LoginService,
BaseRequestOptions,
MockBackend,
provide(Http, {
useFactory: (backend: MockBackend, defaultOptions: BaseRequestOptions) => {
return new Http(backend, defaultOptions);
},
deps: [MockBackend, BaseRequestOptions]
})
]));

it('should return data.',
async(inject([LoginService], (loginService: LoginService) => {
loginService.getLogin().subscribe(
data => console.log(data)
);
})
));

});


However, the data doesn't get logged.
I tried various solutions that I found on SO or on the internet.

One of them was to make a http call to the mockbackend but that just gave me data = undefined.

Answer

You need to inject MockBackend and subscribe for connection, like this:

UPDATE

async(inject([LoginService, MockBackend], (loginService: LoginService, mockBackend:MockBackend) => {
  let mockResponse = new Response(new ResponseOptions({body: {'redirect': 'some string'}}))
  mockBackend.connections.subscribe(c => c.mockRespond(mockResponse));
  loginService.getLogin().subscribe(
    data => console.log(data)
  );
})

For more details go here:

https://angular.io/docs/ts/latest/api/http/testing/index/MockBackend-class.html

Comments