Skip to content

Instantly share code, notes, and snippets.

@dherges
Last active May 18, 2017 18:00
Show Gist options
  • Select an option

  • Save dherges/c5238fe2b9e27a42c0a6659dc56e2e01 to your computer and use it in GitHub Desktop.

Select an option

Save dherges/c5238fe2b9e27a42c0a6659dc56e2e01 to your computer and use it in GitHub Desktop.
Angular Testing Snippets: Services over HTTP
describe(`FeatureService`, () => {
/** ... set up ... **/
it(`should emit 'false' for 401 Unauthorized`,
async(inject([ FeatureService, MockBackend ],
(service: FeatureService, mockBackend: MockBackend) => {
// 0. prepare fake response from `MockBackend`
mockBackend.connections.subscribe((c: MockConnection) => {
// 2a. expect `FeatureSerivice` to make a proper request
expect(c.request.url).toBe('auth/login');
expect(c.request.method).toBe(RequestMethod.Post);
expect(c.request.headers.get('Content-Type'))
.toBe('application/x-www-form-urlencoded');
// 2b. expect request body to contain form data
expect(c.request.getBody()).toBe(/* ... */);
// 3. respond to `FeatureService` with a 401 Unauthorized
c.mockRespond(new Response(new ResponseOptions({
body: '',
status: 401
})));
});
// 1. dispatch the http request
service.login('foo', 'bar')
.subscribe((status: boolean) => {
// 4. ensure that `FeatureService` reports login failure
expect(status).toBeFalsy();
});
})));
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment