2017-03-02 130 views
0

我是angular2的初学者。Angular2 - HTTP调用单元测试

我service.ts会,

import { Injectable } from '@angular/core'; 
import { Http, Response } from '@angular/http'; 
import {Headers, RequestOptions, URLSearchParams} from '@angular/http'; 
import {Observable} from 'rxjs/Observable'; 
import 'rxjs/add/operator/map'; 
import 'rxjs/add/operator/catch'; 
import 'rxjs/add/observable/throw'; 

@Injectable() 
export class HomeService { 

    url : string; 

    constructor(private _http: Http) {} 

    getUserInfo(userId : string) { 

     this.url = "http://localhost:9080/GetUserData"; 

     let content = new URLSearchParams(); 
     content.set('userId', userId.toString()); 

     let headers = new Headers(); 
     headers.append('Content-Type', 'application/x-www-form-urlencoded'); 

     return this._http 
      .post(this.url, content.toString(), {headers: headers}) 
      .map((res: Response) => res.json()) 
      .catch(this.handleError); 
    } 

    handleError (error: Response | any) { 

     let errMsg: string; 
     if (error instanceof Response) { 
      const body = error.json() || ''; 
      const err = body.error || JSON.stringify(body); 
      errMsg = `${error.status} - ${error.statusText || ''} ${err}`; 
     } else { 
      errMsg = error.message ? error.message : error.toString(); 
     } 
     console.error(errMsg); 
     return Observable.throw(errMsg); 
    } 

} 

我已经写单元测试情况下,

import { TestBed, async, inject } from '@angular/core/testing'; 
import { HomeService } from './home.service'; 
import { BaseRequestOptions, Response, ResponseOptions, Http } from '@angular/http'; 
import { MockBackend, MockConnection } from '@angular/http/testing'; 
import {Observable} from 'rxjs/Observable'; 

describe('FacilityPopupService',() => { 
    let subject: HomeService = null; 
    let backend: MockBackend = null; 
    let userid="UID1"; 

    beforeEach(() => { 
    TestBed.configureTestingModule({ 
     providers: [ 
      HomeService, 
      Response, 
     BaseRequestOptions, 
     MockBackend, 
     { 
      provide: Http, 
      useFactory: (backend: MockBackend, defaultOptions: BaseRequestOptions) => { 
      return new Http(backend, defaultOptions); 
      }, 
      deps: [MockBackend, BaseRequestOptions], 
     } 

      ] 
    }); 
    }); 

    beforeEach(inject([HomeService, MockBackend], (userService: HomeService, mockBackend: MockBackend) => { 
    subject = userService; 
    backend = mockBackend; 

    })); 

    it('get Facility list should call endpoint and return it\'s result', (done) => { 
     backend.connections.subscribe((connection: MockConnection) => { 
      let options = new ResponseOptions({ 
      body: JSON.stringify({ success: true }) 
      }); 
      connection.mockRespond(new Response(options)); 
     }); 

     subject.getUserInfo(userid) 
     .subscribe((response) => { 
      expect(response).toEqual({ success: true }); 
      done(); 
     }); 

    }); 

}); 

我想编写测试用例两个成功案例和错误情况。我不知道如何执行catch block。我也不知道如何编写测试用例handleError方法。

我不能在这里涵盖所有可能的场景。你能帮我获得100%的service.ts覆盖率吗?

+0

你要什么情况下有哪些? – BILL

+0

@BILL。更新了问题。请立即检查。 –

回答

1

对于覆盖否定的情况,你可以用非200状态代码来模拟回应。 你可以按照这个例子MockBackend.

it('getUserInfo() while server is down', fakeAsync(() => { 
     let result: any; 
     let catchedError: any; 
     this.userUser.getUserInfo(1) 
      .then((userInfo: any) => result = userInfo) 
      .catch((error: any) => catchedError = error); 
     this.lastConnection.mockRespond(new Response(new ResponseOptions({ 
     status: 404, //here 
     statusText: 'URL not Found', 
     }))); 
     tick(); 
     expect(result).toBeUndefined(); 
     expect(catchedError).toBeDefined(); 
    })); 
}); 
+0

感谢您的答案法案......什么是tick()在这里。当tick()时我收到编译错误。 –

+0

@Human您可以从@ angular/core/testing中导入滴答功能 – BILL

+0

非常好... _ + 1 for u ...请您在** component.ts **中查找问题。 http://stackoverflow.com/questions/42814752/angular2-http-call-code-coverage –

0

您可以将以下代码用于正面情况。

describe('HomeService',() =>{ 
    let homeService:HomeService, 
     mockHttp; 

     beforeEach(() => { 
      mockHttp=jasmine.createSpyObject('mockHttp',['get']) 
      homeService=new HomeService(mockHttp); 

     }); 
     describe('GetbyID', =>{ 
      it('should get the detail of user with passed id', =>{ 
      let user={id:1,name:'some Name'} 
       mockHttp.get.and.returnValue(Observable.of(false)); 
       homeService.getUserInfo(1); 
       expect(mockHttp.get).toHaveBeenCalledWith('your url'); 

      }); 
     }); 
}); 

为负的情况下:犯了一个错误的URL,并检查调用失败和错误处理方法被调用或没有。

+0

有关负面情况的任何想法? –

+0

@HumanBeing更新答案 – Aravind