简体   繁体   English

angular2 - 如何在http.post单元测试中模拟错误

[英]angular2 - how to simulate error on http.post unit test

I m writing a Uni-test for a login Method with an HTTP.post call, like: 我正在使用HTTP.post调用为登录方法编写Uni-test,如:

this.http.post( endpoint, creds, { headers: headers})
        .map(res => res.json())
        .subscribe(
        data => this.onLoginComplete(data.access_token, credentials),  
        err => this.onHttpLoginFailed(err),
        () => this.trace.debug(this.componentName, "Login completed.")
    );

The problem is that i'm not able to simulate the error branch; 问题是我无法模拟错误分支; everytime is called the onLoginComplete Method; 每次都被称为onLoginComplete方法;

here is my test: 这是我的测试:

it("check that  Atfer Login, console show an error ", inject(
  [TraceService, Http, MockBackend, WsiEndpointService],
  (traceService: TraceService, http: Http, 
   backend: MockBackend, wsiEndpoint: WsiEndpointService) => {

  let tokenTest: number =  404 ;

  let response: ResponseOptions = null {} // i think i have to modify this

  let connection: any;

  backend.connections.subscribe((c: any) => connection = c);

  let authService: AuthService = new AuthService(http, Service1, Service2);

  authenticationservice.login({ "username": "a", "password": "1" });

  connection.mockRespond(new Response(response));

  expect(ERROR);

}));

Thanks again to everyone. 再次感谢大家。

First you need to override the XHRBackend class by the MockBackend one: 首先,您需要通过MockBackend覆盖XHRBackend类:

describe('HttpService Tests', () => {
  beforeEachProviders(() => {
    return [
      HTTP_PROVIDERS,
      provide(XHRBackend, { useClass: MockBackend }),
      HttpService
    ];
  });

  (...)
});

Notice that HttpService is the service that uses the Http object and I want to test. 请注意, HttpService是使用Http对象的服务,我想测试。

Then you need to inject the mockBackend and subscribe on its connections property. 然后你需要注入mockBackend并订阅其connections属性。 When a request is sent, the corresponding callback is called and you can specify the response elements like the body. 发送请求时,将调用相应的回调,您可以指定响应元素,如正文。 The service will receive this response as the response of the call. 该服务将接收此响应作为呼叫的响应。 So you'll be able to test your service method based on this. 因此,您将能够基于此测试您的服务方法。

Below I describe how to test the getItems method of the HttpService : 下面我将介绍如何测试HttpServicegetItems方法:

it('Should return a list of items', inject([XHRBackend, HttpService, Injector], (mockBackend, httpService, injector) => {
  mockBackend.connections.subscribe(
    (connection: MockConnection) => {
      connection.mockRespond(new Response(
        new ResponseOptions({
          body: [ { id: '1', label: 'item1' }]
        })));
      });

  httpService.getItems().subscribe(
    items => {
      expect(items).toEqual([ { id: '1', label: 'item1' }]);
    });
  });
});

Here is the code of getItems method of the HttpService : 这是HttpServicegetItems方法的代码:

@Injectable()
export class HttpService {
  constructor(private http:Http) {
  }

  getItems(): Observable<any[]> {
    return this.http.get('/items').map(res => res.json());
  }
}

To simulate an error simply use the mockError method instead of the mockResponse one: 为了模拟一个错误简单地使用mockError方法,而不是mockResponse之一:

  mockBackend.connections.subscribe(
    (connection: MockConnection) => {
      connection.mockError(new Error('some error'));
    });

You can simulate an error like this: 你可以模拟这样的错误:

connection.mockError(new Response(new ResponseOptions({
    body: '',
    status: 404,
})));

I created a small class 我创建了一个小班

import {ResponseOptions, Response} from '@angular/http';

export class MockError extends Response implements Error {

    name: any;
    message: any;

    constructor(status: number, body: string = '') {
        super(new ResponseOptions({status, body}));
    }
}

which can use like this 可以这样使用

connection.mockError(new MockError(404));

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

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