【问题标题】:Jasmine toThrowError fail, message "Error: Actual is not a function"Jasmine toThrowError 失败,消息“错误:实际不是函数”
【发布时间】:2018-06-27 13:48:27
【问题描述】:

我正在构建 Jasmine 规范并编写 toThrowError 测试。

 it("Should give time travel error", () => {
        const errorMsg = Logger.getLogsBetweenDates( { 
              fromDate : new Date("2017-01-06"),
              toDate : new Date("2017-01-05")});

        expect(errorMsg).toThrowError("Time travel error: fromDate must be befor toDate");
});

我得到“错误:实际不是函数”,没有额外的细节。

  • Actual 是什么?
  • Logger.getLogsBetweenDates函数急剧抛出错误,测试总是失败。我做错了什么?

【问题讨论】:

    标签: javascript node.js unit-testing jasmine


    【解决方案1】:

    实际值是多少?

    顾名思义,Actual 是包含测试函数实际结果的变量。你测试的函数实际上返回了什么。

    然后,Jasmine 将 Actual 值与您的 expect 值进行比较。 看到源代码here就更容易理解了。

    它发生在代码中,因为Logger.getLogsBetweenDates 抛出错误,errorMsg 没有结果;所以Actualundefinedexpect 函数将undefined 与错误消息进行比较。

    我做错了什么?

    你需要在expect函数内部调用被测函数,像这样:

    it("Should give time travel error", () => {    
         expect(() => {
                 Logger.getLogsBetweenDates( { 
                      fromDate : new Date("2017-01-06"),
                      toDate : new Date("2017-01-05")})
                }).toThrowError("Time travel error: fromDate must be befor toDate");
    });
    

    如图here

    【讨论】:

    • 此外,您还可以将函数保存为变量并在测试中引用它,例如const failingFunction = () => [call-to-function-with-parameters]; 然后做expect(failingFunction).toThrowError('Error message');
    • 不允许进行 1 字符的编辑,所以留下评论 - 期望内的功能块缺少右括号!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-21
    相关资源
    最近更新 更多