【问题标题】:how to write unit test for catching the exception that exception throw in asynchronous block (observable or promise) in a function?如何编写单元测试来捕获函数中异步块(可观察或承诺)中异常抛出的异常?
【发布时间】:2019-06-17 09:12:29
【问题描述】:

我想为此函数 getData() 编写单元测试。

getData(){
  this.service.getvalues().subscribe(
        results => {
        },
        err => {
            throw err;
        }
    );
}

我试过了

it('', async(() => {
      serviceSpy.getvalues.and.returnValue(throwError({}));
      try {
        component.getData({});
      } catch (error) {
        console.log(error);
      }
    }));

这个 getData 函数没有返回任何东西。 我将 asnyc() 放在它的块中,以确保该区域内的所有异步调用都完成后,测试将自动完成。

我的问题是我无法捕捉到该错误 因为那个异常是在异步块中抛出的

【问题讨论】:

    标签: angular unit-testing angular6


    【解决方案1】:

    抛出错误会抛出错误,无论它在哪里完成。

    我已经有一段时间没有使用它了,但是这种测试的语法应该是

    it('', () => {
      serviceSpy.getvalues.and.returnValue(throwError({}));
      expect(() => component.getData({})).toThrow(/* some params */);
    });
    

    不知道你为什么也使用异步,所以我把它删除了。

    【讨论】:

      猜你喜欢
      • 2017-11-25
      • 2014-06-13
      • 2018-04-05
      • 1970-01-01
      • 1970-01-01
      • 2012-02-03
      • 2018-04-09
      • 1970-01-01
      • 2017-08-13
      相关资源
      最近更新 更多