【问题标题】:How-to force a Jasmine test response to go through the rxjs catch如何强制 Jasmine 测试响应通过 rxjs 捕获
【发布时间】:2017-06-30 19:01:50
【问题描述】:

我有如下服务:

createProdCategory( prodcategory: IProdCategory ) {
    console.log(prodcategory);
    return this.http.post( this.url, prodcategory )
        .map( ( response: Response ) => response.json( ) )
        .catch( this.handleError );
}
...
handleError( error: any ) {
    console.error( error );
    return Observable.throw( error.json( ).error || 'Service error' );
}

我想通过 handleError 函数通过 RXJS catch 测试路径。我的规格如下:

 it( 'should handle an error on create...', async(() => {
  let mockData: ProdCategory = mockDatum[ 2 ];
  backend.connections.subscribe((connection) => {
    let response: Response = new Response(
      new ResponseOptions( { body: JSON.stringify( { error: `${errMsg}` } ), status: 404, statusText: `${errMsg}` } ));
    connection.mockRespond( response );
  });
  expect( 
      sut.createProdCategory( mockData ).subscribe((resp) => {
          fail( 'handleError: expected error...' );
      } )
    ).toThrowError( errMsg );
}));

很遗憾,catch 没有被调用,也没有抛出错误信息。如何强制响应通过捕获。

【问题讨论】:

    标签: angular jasmine rxjs


    【解决方案1】:

    您需要模拟一个错误作为响应。

    所以不是

      connection.mockRespond( response );
    

    使用

      connection.mockError(response);
    

    然后在订阅中你必须处理错误情况:

    sut.createProdCategory( mockData ).subscribe(
        () => {},
        error => {
           expect(error)......
         }
    );
    

    【讨论】:

    • 感谢 Julia,它现在正在经历 handleError。我有一些工作要做。
    • 测试现在如下所示: sut.createProdCategory( mockData ).subscribe((resp) => { ... }, ( error ) => { expect( error ).toEqual( errMsg ); }
    猜你喜欢
    • 2016-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-13
    相关资源
    最近更新 更多