Angular2 - HTTP呼叫单元测试 [英] Angular2 - HTTP call unit testing

查看:94
本文介绍了Angular2 - HTTP呼叫单元测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是angular2的初学者。

I am a beginner of angular2.

我的service.ts将是,

My service.ts will be,

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);
    }

}

我写了单元测试用例as,

I have written the unit test case as,

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 块。另外我不知道如何为 handleError 方法编写测试用例。

I want to write the test case for both success case and error case. I don't know how how to execute catch block. Also I don't know how to write test case for handleError method .

我不能在这里涵盖所有可能的情况。能否帮助我获得100%的服务保障。

I cannot cannot cover all the possible scenarios here. Can you please help me to get 100% coverage for the service.ts.

推荐答案

为了覆盖否定案例你可以模拟回复非200状态代码。
您可以按照此示例 MockBackend 。

For covering negative case you can mock response with non-200 status code. You can follow this example 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();
     }));
});

这篇关于Angular2 - HTTP呼叫单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆