简体   繁体   English

单元测试map.catch angular4服务

[英]Unit Testing map.catch angular4 services

Can any one please suggest how to test the below catch function in spec.ts file? 有人可以建议如何在spec.ts文件中测试以下catch函数吗?

 getTemplate(){
        this._http.get('http//localhost:8080/new').map((response : Response) => response.json())).catch(this.serverError);
      }
      private serverError(err: any) {
        console.log('sever error:', err); // debug
        if(err instanceof Response) {
         //return Observable.throw(err.json().error || 'backend server error');
          // if you're using lite-server, use the following line
          // instead of the line above:
        return Observable.throw(err.text() || 'backend server error');
        }
        return Observable.throw(err || 'backend server error');
      }

In order to test that you need to receive the HttpErrorResponse from the server. 为了测试您需要从服务器接收HttpErrorResponse。 To test this you can write a small interceptor, and throw an error while monitoring the response, then your catch will be triggered. 为了测试这一点,您可以编写一个小的拦截器,并在监视响应时抛出错误,然后将触发捕获。

Check this post out, it has reference to both how to write an interceptor and how to generate the httperror response when requied, 看看这篇文章,它同时参考了如何编写拦截器以及在需要时如何生成httperror响应,

https://medium.com/codingthesmartway-com-blog/angular-4-3-httpclient-accessing-rest-web-services-with-angular-2305b8fd654b https://medium.com/codingthesmartway-com-blog/angular-4-3-httpclient-accessing-rest-web-services-with-angular-2305b8fd654b

In the code below you also need to make sure that all the setup and imports are done properly, below code snippet will trigger the httperror response, to be precise it would be Http 404. 在下面的代码中,您还需要确保所有设置和导入均正确完成,下面的代码段将触发httperror响应,确切地说,它将是Http 404。

Update 1 更新1

here is how a sample test case file would look like, assume your service name is YourService 这是一个示例测试用例文件的样子,假设您的服务名称是YourService

import {Injectable, ReflectiveInjector} from '@angular/core';
import {async, fakeAsync, tick} from '@angular/core/testing';
import {BaseRequestOptions, ConnectionBackend, Http, RequestOptions} from '@angular/http';
import {Response, ResponseOptions} from '@angular/http';
import {MockBackend, MockConnection} from '@angular/http/testing';

import { YourService } from './serviceIndependent.service';


describe('MockBackend NameService Example', () => {
  beforeEach(() => {
    this.injector = ReflectiveInjector.resolveAndCreate([
      {provide: ConnectionBackend, useClass: MockBackend},
      {provide: RequestOptions, useClass: BaseRequestOptions},
      Http,
      YourService,
    ]);
    this.yourService = this.injector.get(YourService);
    this.backend = this.injector.get(ConnectionBackend) as MockBackend;
    this.backend.connections.subscribe((connection: any) => this.lastConnection = connection);
  });


  it('getNames() while server is not Reachable', fakeAsync(() => {
       let result: String[];
       let catchedError: any;
       this.yourService.getNames()
           .then((names: String[]) => result = names)
           .catch((error: any) => catchedError = error);
       this.lastConnection.mockRespond(new Response(new ResponseOptions({
         status: 404,
         statusText: 'URL not Found',
       })));
       tick();
       expect(result).toBeUndefined();
       expect(catchedError).toBeDefined();
     }));
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM