10

そのため、angular2 コンポーネントとサービスをテストしています。

これまでのところ、以下のようにサービス内の get リクエストをモックするために mockBackend を使用しました。

/* tslint:disable:no-unused-variable */

import { MockBackend } from '@angular/http/testing';
import { Http, ConnectionBackend, BaseRequestOptions, Response, ResponseOptions } from '@angular/http';
import { PagesService } from './pages.service';
import { tick, fakeAsync } from '@angular/core/testing/fake_async';
import { inject, TestBed } from '@angular/core/testing/test_bed';
import {GlobalService} from './../../shared/global.service';

describe('PagesService', () => {
  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [
        {
          provide: Http, useFactory: (backend: ConnectionBackend, defaultOptions: BaseRequestOptions) => {
            return new Http(backend, defaultOptions);
          }, deps: [MockBackend, BaseRequestOptions]
        },
        { provide: PagesService, useClass: PagesService },
        { provide: GlobalService, useClass: GlobalService },
        { provide: MockBackend, useClass: MockBackend },
        { provide: BaseRequestOptions, useClass: BaseRequestOptions }
      ]
    });
  });

  //should retrive all search results
  it('should retrieve all search results',
    inject([PagesService, MockBackend], fakeAsync((pagesService: PagesService, mockBackend: MockBackend) => {
      let res: Response;
      mockBackend.connections.subscribe(c => {
        expect(c.request.url).toBe('http://localhost:3200/pm/pages/');
        let response = new ResponseOptions({
          body: '[{"name": "Rapid"}, {"name": "NGBC"}]'});
          c.mockRespond(new Response(response));
        });
        pagesService.getAllpages().subscribe((response) => {
           res = response;              
        });
        tick();
        expect(res[0].name).toBe('Rapid');
     }))
  );
 it('should fetch by Page id',
  inject([PagesService, MockBackend], fakeAsync((pagesService: PagesService, mockBackend: MockBackend) => {
    let res;
    mockBackend.connections.subscribe(c => {
      let page_id:string='2';
      expect(c.request.url).toBe('http://localhost:3200/pm/pages/'+page_id);
      let response = new ResponseOptions({body: '[{"id": 1, "name": "Rapid"}, {"id": 2, "name": "NGBC"}]'});
      c.mockRespond(new Response(response));
    });
    pagesService.getPageById('2').subscribe((response) => {
      res = response;
   });
   tick();
   expect(res[1].name).toBe('NGBC');
   }))
 ); 
});

私のservice.tsを見たい場合は、以下のようになります:

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 + '/pm/pages/')
            .map((res: Response) => res.json()).catch(this.handleError);
    }

    getPageById(page_id: string) {
        return this.http.get(this.baseUrl + '/pm/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+'/pm/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+'/pm/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+'/pm/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 + '/pm/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');
    }
}

上記のサービスから、正常に動作しているため、service.spec.ts ファイルに getAllPages() & getPageById() メソッドを正しく実装しました。

メソッドのテストケースの実装方法を知りたいですsavePage() , updatePage() , deletePage()

入力はありますか?

前もって感謝します。

4

1 に答える 1