Testing angular2 services with constructor with HTTP dependency

How to write a jasmine test case for the next class with a constructor that has a dependency on http

import {Injectable} from 'angular2/core'; import {Http, HTTP_PROVIDERS} from 'angular2/http'; @Injectable() export class MockUserService { items:Array<any>; constructor(http:Http){ http.get('http://127.0.0.1:8080/src/data/names.json') .subscribe(res => { this.items = res; console.log('results found'); }) } } 

I tried as follows:

  it('Testing user login', inject([MockUserService,Http], (mockUserService:MockUserService ) => { let http:Http; let mockUserService: MockUserService = new MockUserService(http); expect(1+1).toEqual(2); }); ); 

I get a DI error: DI error image

+7
angular jasmine karma-jasmine
source share
2 answers

This test https://github.com/angular/angular/blob/master/modules/angular2/test/http/http_spec.ts#L104 uses return new Http(backend, defaultOptions); where the backend is MockBackend ( import {MockBackend, MockConnection} from 'angular2/src/http/backends/mock_backend';

+1
source

You can use beforeEachProviders for DI easily, as shown below:

 beforeEachProviders(() => [ HTTP_PROVIDERS, MockUserService ]); describe('MockUser Service', () => { it('Testing user login', inject([MockUserService], (service: MockUserService) => { expect(1 + 1).toEqual(2); })); }); 

Hope this helps you (at least 6 months ago).

+1
source

All Articles