Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing angular2 service having constructor with http dependency

How to write jasmine test case for the following class having constructor which is having 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 in following way ,

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

  });
  );

I am getting DI error: DI error Image

like image 248
vi fi Avatar asked Jan 02 '16 04:01

vi fi


People also ask

What is SpyOn in Angular unit testing?

SpyOn is a Jasmine feature that allows dynamically intercepting the calls to a function and change its result.

Which function is used to inject a service into a test function?

To test a service, you set the providers metadata property with an array of the services that you'll test or mock. content_copy let service: ValueService; beforeEach(() => { TestBed. configureTestingModule({ providers: [ValueService] }); }); Then inject it inside a test by calling TestBed.

What is the correct way to trigger a click event on a button when testing an Angular component?

For click event we can use triggerEventHandler method of Angular DebugElement class. We can also call native JavaScript click method of button. On click of button, we call a component method and it is possible that our component method has other dependencies to execute.

Is the phase where the code behavior is checked and verified?

Assert is the phase where the code behavior is checked and verified. For example, the actual output is compared to the expected output.


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 backend is a MockBackend (import {MockBackend, MockConnection} from 'angular2/src/http/backends/mock_backend';

like image 148
Günter Zöchbauer Avatar answered Nov 14 '22 23:11

Günter Zöchbauer


You can use beforeEachProviders to DI easily like below:

beforeEachProviders(() => [
  HTTP_PROVIDERS,
  MockUserService
]);

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

I hope this will help you(of at least 6 months ago).

like image 24
mgmg Avatar answered Nov 14 '22 23:11

mgmg