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

Tex*_*xas 11 javascript tdd jasmine karma-runner karma-jasmine

我正在尝试在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(' ');
};
Run Code Online (Sandbox Code Playgroud)

我在错误处理方面遇到问题.如果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');
});
Run Code Online (Sandbox Code Playgroud)

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

控制台消息是:预期函数抛出'Inval ...'但它抛出错误:参数组合无效.

我不明白,我应该怎么做这些信息.

编辑:这很奇怪,因为它与Jasmine v.1.3一起使用,但它与jasmine v.2.3 ie或与业力无关,尽管代码基于茉莉.

try*_*lly 12

TL; DR

使用Jasmine 2,匹配器语义发生了变化,并且有了一个新的匹配器.

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

NTL; TR

从Jasmine 2.x开始,有一个新的Matcher toThrowError()和Jasmine toThrow()成为一种新的语义.

  • toThrow()应该用来检查是否有任何错误被抛出或检查是否有消息Error(更具体:那是什么instanceof Error)
  • toThrowError()应该用于检查是否抛出了特定错误,或者错误消息是否等于期望值

内部toThrow(x)对抛出的错误进行相等检查x.如果错误和x都是instanceof Error(TypeError例如也是如此)Jasmine检查===两侧message属性的相等性(一般).

表单toThrowError(x)检查错误消息是否等于或匹配x(字符串或RegExp)

另一种形式toThrowError(t, x)检查错误是否为类型t且消息等于或匹配x(字符串或RegExp)

看到