Hi, I'm relatively new to Angular2, karma and jasmine. I am currently using Angular 2 RC4 Jasmine 2.4.x I have an Angular 2 service that periodically calls the http service, for example:
getDataFromDb() { return Observable.timer(0, 2000).flatMap(() => { return this.http.get(this.backendUrl) .map(this.extractData) .catch(this.handleError); }); }
Now I want to test the functionality. For testing purposes, I just tested "http.get" on a separate function without Observable.timer by doing:
const mockHttpProvider = { deps: [MockBackend, BaseRequestOptions], useFactory: (backend: MockBackend, defaultOptions: BaseRequestOptions) => { return new Http(backend, defaultOptions); } } describe('data.service test suite', () => { var dataFromDbExpected: any; beforeEachProviders(() => { return [ DataService, MockBackend, BaseRequestOptions, provide(Http, mockHttpProvider), ]; }); it('http call to obtain data', inject( [DataService, MockBackend], fakeAsync((service: DataService, backend: MockBackend) => { backend.connections.subscribe((connection: MockConnection) => { dataFromDbExpected = 'myData'; let mockResponseBody: any = 'myData'; let response = new ResponseOptions({ body: mockResponseBody }); connection.mockRespond(new Response(response)); }); const parsedData$ = service.getDataFromDb() .subscribe(response => { console.log(response); expect(response).toEqual(dataFromDbExpected); }); }))); });
I obviously want to test the whole function using Observable.timer. I think it would be possible to use TestScheduler from the rxjs framework, but how can I say only to repeat the timer function x times? I can not find the documentation using it in the context of typescript.
Edit: I am using rxjs 5 beta 6
Edit: Added a working example for the final version of Angular 2.0.0:
describe('when getData', () => { let backend: MockBackend; let service: MyService; let fakeData: MyData[]; let response: Response; let scheduler: TestScheduler; beforeEach(inject([Http, XHRBackend], (http: Http, be: MockBackend) => { backend = be; service = new MyService(http); fakeData = [{myfake: 'data'}]; let options = new ResponseOptions({ status: 200, body: fakeData }); response = new Response(options); scheduler = new TestScheduler((a, b) => expect(a).toEqual(b)); const originalTimer = Observable.timer; spyOn(Observable, 'timer').and.callFake(function (initialDelay, dueTime) { return originalTimer.call(this, initialDelay, dueTime, scheduler); }); })); it('Should do myTest', async(inject([], () => { backend.connections.subscribe((c: MockConnection) => c.mockRespond(response)); scheduler.schedule(() => { service.getMyData().subscribe( myData => { expect(myData.length).toBe(3, 'should have expected ...'); }); }, 2000, null); scheduler.flush(); }))); });