gpt4 book ai didi

javascript - Jasmine 在 expect().toThrow 上抛出错误,而不是识别抛出的错误

转载 作者:可可西里 更新时间:2023-11-01 02:39:25 26 4
gpt4 key购买 nike

我正在尝试实现在 javascript 中学习测试驱动开发方面打印钻石的功能。

Diamond.prototype.outerSpace = function (current, widest) {

var currentValue = this.getIndexOf(current);
var widestValue = this.getIndexOf(widest);

if (currentValue > widestValue) {
throw new Error('Invalid combination of arguments');
}

var spaces = widestValue - currentValue;
return new Array(spaces + 1).join(' ');
};

我在错误处理方面遇到了问题。如果 currentValue 大于 widestValue,上面的函数应该抛出一个错误。

这是我代表测试/规范的片段:

it ("should throw an exception, if it is called with D and C", function () {
var outerSpace = diamond.outerSpace.bind(diamond, 'D', 'C');
expect(outerSpace).toThrow('Invalid combination of arguments');
});

我也尝试过在 expect(..) 中使用匿名函数,但这也没有用。

控制台消息是:预期函数抛出“无效...”但它抛出错误:无效的参数组合。

我不明白,我应该如何处理这些信息。

编辑:这很奇怪,因为它与 Jasmine v.1.3 一起工作,但它没有与 jasmine v.2.3 一起工作,即或与 karma 一起工作,尽管代码基于 jasmine。

最佳答案

长话短说

在 Jasmine 2 中,匹配器的语义发生了变化,并且有一个新的匹配器。

使用 toThrowError("<message>")toThrow(new Error("<message>")))

NTL;TR

自 Jasmine 2.x 以来,有一个新的匹配器 toThrowError()和 Jasmine 的 toThrow()有了新的语义。

  • toThrow()应该用于检查是否有任何错误被抛出 或检查 Error 的消息(更具体:某事是 instanceof Error )
  • toThrowError()应该用于检查是否引发了特定错误,或者错误消息是否符合预期

内部toThrow(x)根据 x 对抛出的错误进行相等性检查.如果错误和xinstanceof Error (例如 TypeError 也是如此)Jasmine 检查 === 双方是否相等(通常为 message)属性。

表格toThrowError(x)检查错误消息是否等于或匹配 x (字符串或正则表达式)

另一种形式toThrowError(t, x)检查错误是否属于 t 类型消息等于或匹配 x (字符串或正则表达式)

关于javascript - Jasmine 在 expect().toThrow 上抛出错误,而不是识别抛出的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33856063/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com