【问题标题】:Can't seem to catch error when using Jasmine toThrowError使用 Jasmine toThrowError 时似乎无法捕获错误
【发布时间】:2020-01-22 20:52:42
【问题描述】:

我开始尝试 jasmine,我想使用 toThrowError() 函数,但我的测试不想成功。

我有一个函数会抛出错误:

test.service.ts

test(list:{}){ 
    if(list == null){
        throw new TypeError();
    }
    else{
        // do something...
    }
}

还有我的测试:

it('shall throw an error', inject()
    [
        TestService
    ],
    (
        testService: TestService
    ) => {
        let test = testService.test(null);
        expect(test).toThrowError(TypeError);
    }
);

我的测试失败并出现 Uncaught TypeError(当我调用它时,我是在 try catch 中进行的)。

【问题讨论】:

    标签: angular typescript jasmine


    【解决方案1】:

    你应该期待一个函数,它用null 调用你的函数,会抛出一个错误。现在,您期望调用该函数的结果会引发错误,但实际上并没有发生。

    expect(() => testService.test(null)).toThrowError(TypeError);
    

    换句话说,测试中的以下行:

    let test = testService.test(null);
    

    使用null 执行test 函数,抛出TypeError。因为它不在expect 之内,所以被 jasmine 认为是“未捕获”。抛出错误后,不执行任何其他操作。永远不会调用 expect(test).toThrowError(TypeError); 行。

    上面显示的代码将一个函数传递给expect。当 jasmine 运行该函数时,它将抛出TypeError,并满足toThrowError(TypeError) 条件。

    【讨论】:

    • 你能解释一下吗?我没有得到解释?
    • 是的,我终于明白了。谢谢。
    【解决方案2】:
    • 您可能必须像 here 那样从间谍那里抛出错误。

    • 你在抛出错误之前就已经预料到了

      spyOn(foo, "setBar").and.throwError("quux");
      

    【讨论】:

      猜你喜欢
      • 2020-02-19
      • 1970-01-01
      • 2020-11-14
      • 1970-01-01
      • 2018-06-27
      • 2021-03-08
      • 2023-01-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多