Skip to content

Instantly share code, notes, and snippets.

@deebloo
Last active December 3, 2018 09:01
Show Gist options
  • Save deebloo/15b76e1e8dbd3acd405fbd7d458fd659 to your computer and use it in GitHub Desktop.
Save deebloo/15b76e1e8dbd3acd405fbd7d458fd659 to your computer and use it in GitHub Desktop.
How to mock http requests with angular2's http module
// import core testing libs
import {
beforeEach,
addProviders,
it,
describe,
expect,
inject
} from '@angular/core/testing';
// import http
import {
HTTP_PROVIDERS,
XHRBackend,
Response,
ResponseOptions
} from '@angular/http';
// imort http testing libs
import { MockBackend, MockConnection } from '@angular/http/testing';
// import your service
import { LoginService} from './login.service.spec';
describe('Service: Login', () => {
// add providers
// NOTE: notice we are providing XHRBackend with
// the MockBackend class from the http testing lib
beforeEach(() => {
addProviders([
HTTP_PROVIDERS,
{ provide: XHRBackend, useClass: MockBackend },
LoginService,
]);
});
it('should log in the user and cache details',
inject([LoginService, XHRBackend], (service: LoginService, mockBacked: MockBackend) => {
// subscribe to connections to mock backend
mockBacked.connections.subscribe((connection: MockConnection) => {
// call mock respond of the connection
// send in a Response Object
connection.mockRespond(new Response(
// pass in new isntance of Response Options
new ResponseOptions({
body: { fname: 'Danny', lname: 'Blue' }
})
));
});
// test your service
service
.login({ email: 'foo@email.com', password: 'password1' })
.subscribe(res => {
expect(res.fname).toBe('Danny');
});
}));
});
@yacineMTB
Copy link

thanks lol

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment