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

Ant*_*tsu 6 post unit-testing http angular

我正在使用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.")
    );
Run Code Online (Sandbox Code Playgroud)

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

}));
Run Code Online (Sandbox Code Playgroud)

再次感谢大家.

Thi*_*ier 18

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

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

  (...)
});
Run Code Online (Sandbox Code Playgroud)

请注意,这HttpService是使用该Http对象的服务,我想测试.

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

下面我将介绍如何测试getItems方法HttpService:

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' }]);
    });
  });
});
Run Code Online (Sandbox Code Playgroud)

这是getItems方法的代码HttpService:

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

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

要模拟错误,只需使用mockError方法而不是以下方法mockResponse:

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

  • 小问题:除了字符串之外,你如何使用mockError添加错误http状态代码(404,422,500等)?就我而言,一些服务器响应不会返回任何内容.由于某种原因,我没有找到一个显示任何地方的例子. (11认同)