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

Unit testing angular2-如何在http.post单元测试上模拟错误,unit-testing,http,post,angular,Unit Testing,Http,Post,Angular,我正在为带有HTTP.post调用的登录方法编写一个Uni测试,如: this.http.post( endpoint, creds, { headers: headers}) .map(res => res.json()) .subscribe( data => this.onLoginComplete(data.access_token, credentials), err => this.onHttpLo

我正在为带有HTTP.post调用的登录方法编写一个Uni测试,如:

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.")
    );
问题是我无法模拟错误分支;每次都称为onLoginComplete方法

这是我的测试:

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

}));

再次感谢大家。

首先,您需要通过
MockBackend
覆盖
XHRBackend
类:

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

  (...)
});
请注意,
HttpService
是使用
Http
对象的服务,我想测试它

然后,您需要注入mockBackend并订阅它的
connections
属性。当发送请求时,会调用相应的回调,您可以指定响应元素,如body。服务将接收此响应作为呼叫响应。因此,您将能够基于此测试您的服务方法

下面我将描述如何测试
HttpService
getItems
方法:

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' }]);
    });
  });
});
@Injectable()
export class HttpService {
  constructor(private http:Http) {
  }

  getItems(): Observable<any[]> {
    return this.http.get('/items').map(res => res.json());
  }
}
以下是
HttpService
getItems
方法的代码:

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' }]);
    });
  });
});
@Injectable()
export class HttpService {
  constructor(private http:Http) {
  }

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

您可以模拟如下错误:

connection.mockError(new Response(new ResponseOptions({
    body: '',
    status: 404,
})));
我创建了一个小班

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}));
    }
}
哪个可以像这样使用

connection.mockError(new MockError(404));

小问题:除了字符串之外,您如何使用mockError添加错误http状态码(404422500等)?在我的例子中,一些服务器响应只返回该响应。由于某种原因,我还没有找到一个例子来显示它在任何地方。@Luciomolinedo,这是因为当前的RC不支持它。请参阅,以获取使其可用的错误修复。与此同时,糟糕的单元测试将不得不再次受到冲击。我想知道这个解决方案是否可以应用到当前版本的angular(2.4)?我试着在这里适应它:没有用。。。有人能给点建议吗?