2

I am learning angular2 RC5 now. I want to test following service in angular2 RC5 but I am not able to configure it somehow.

import { Injectable } from '@angular/core';
import { Http, Response,Headers } from '@angular/http';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import {Observable} from 'rxjs/Observable';
import {GlobalService} from './../../shared/global.service';
@Injectable()
export class PagesService {
    private headers = new Headers();
    public baseUrl:string;
    constructor(private http: Http,private _globalService:GlobalService) {
        this.baseUrl=this._globalService.baseUrl;
    }
    getAllpages() {
        return this.http.get(this.baseUrl + '/pages/')
        .map((res: Response) => res.json()).catch(this.handleError);
    }

    getPageById(page_id: string) {
        return this.http.get(this.baseUrl + '/pages/' + page_id)
        .map((res: Response) => res.json()).catch(this.handleError);
    }

   savePage(page: Object) {
       this.headers=new Headers();
       this.headers.append('Content-Type', 'application/json');
       let url = this.baseUrl+'/pages/';
       let data={};
       data["data"]=page;
       return this.http.post(url, JSON.stringify(data),{headers: this.headers})
       .map((res: Response) => res.json()).catch(this.handleError);
   }

   updatePage(page: any) {
       this.headers=new Headers();
       this.headers.append('Content-Type', 'application/json');
       let url = this.baseUrl+'/pages/'+page._id;
       let data={};
       data["data"]=page;
       return this.http.put(url, JSON.stringify(data),{headers: this.headers})
       .map((res: Response) => res).catch(this.handleError);
   }

   deletePage(page_id: string) {
     this.headers=new Headers();
     this.headers.append('Content-Type', 'application/json');
     let url = this.baseUrl+'/pages/';
     return this.http.delete(url + page_id,{headers: this.headers,body: ''})
     .map((res: Response) => res).catch(this.handleError);
   }

   mergePage(page: Object) {
      return this.http.post(this.baseUrl + '/pages/',JSON.stringify(page))
        .map((res: Response) => res.json()).catch(this.handleError);
   }

   handleError(error: any) {
      console.error(error);
      return Observable.throw(error.json().error || 'Server error');
   }
}

I want to test every method in this service, any inputs?

Bhushan Gadekar
  • 13,485
  • 21
  • 82
  • 131

1 Answers1

1

To test an Angular2 service you need to import it in unit test and just test methods one after another:

describe('Service: LanguagesService', () => {   let service;
     //setup   beforeEachProviders(() => [
    LanguagesService   ]);
     beforeEach(inject([LanguagesService], s => {
    service = s;   }));
     //specs   it('should return available languages', () => {
    let languages = service.get();
    expect(languages).toContain('en');
    expect(languages).toContain('es');
    expect(languages).toContain('fr');
    expect(languages.length).toEqual(3);   }); })

Really useful links :

https://angular.io/docs/ts/latest/testing/ http://twofuckingdevelopers.com/2016/01/testing-angular-2-with-karma-and-jasmine/

https://developers.livechatinc.com/blog/testing-angular-2-apps-dependency-injection-and-components/

https://medium.com/google-developer-experts/angular-2-unit-testing-with-jasmine-defe20421584#.917ak4f6v (example is based on it)

Keywords: jasmine + testing angular2.

jmachnik
  • 1,120
  • 9
  • 19
  • Link-only answers are discouraged. Please add the relevant parts directly to the answer. – Günter Zöchbauer Sep 06 '16 at 07:49
  • 1
    @GünterZöchbauer ,edited, question was overall so is the answer. I had an impression that he only seeks for guidance. – jmachnik Sep 06 '16 at 08:07
  • 1
    Even though a link might be helpful, it's still discouraged. The answer should also provide value to future visitors, not only the one who asked and links are prone to become stale. It's much better now :) – Günter Zöchbauer Sep 06 '16 at 08:09
  • I get the idea, but I am not able to understand that if my mock service extends a service I want to test, It always shows error `No provider for http` even though I have not injected http in it. I dont know how to inject instance of my service into mock-service. @JacobM – Bhushan Gadekar Sep 06 '16 at 12:25
  • @JacobM its for the component... I have injected it in appModule.. I was talking about test files... when I am running `ng test` only then I am getting above error. – Bhushan Gadekar Sep 06 '16 at 13:09
  • I am not able to test it now, but you must inject the HTTP because your service is using it. I think it's because you don't have the whole application in Jasmine, but only the class you test. Check this out: http://chariotsolutions.com/blog/post/testing-http-services-angular-2-jasmine/ – jmachnik Sep 06 '16 at 13:17