微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

我正在使用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.")
    );

问题是我无法模拟错误分支;每次都被称为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属性.发送请求时,将调用相应的回调,您可以指定响应元素,如正文.该服务将接收此响应作为呼叫的响应.因此,您将能够基于此测试您的服务方法.

下面我将介绍如何测试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' }]);
    });
  });
});

这是HttpService的getItems方法代码

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

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

要模拟错误,只需使用mockerror方法而不是mockResponSEOne:

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

原文地址:https://www.jb51.cc/angularjs/140927.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐