用于抛出 someObject 的 Jasmine 测试匹配器

Jasmine testing matcher for throw someObject

我有一个函数可以在某些情况下抛出一些对象。我用 toThrow 写了一个茉莉花期望匹配器,但它不起作用。不知道为什么会失败。任何帮助将不胜感激。

  fit("The 'toThrow' matcher is for some object", function() {
    function baz(x) {   // this is the function to test
      if(x === 1) {
        return 1;
      } else {
        throw {status: 515};
      }
    };
    expect(baz(1)).toBe(1); // matched perfect.
    expect(baz(2)).toThrow({status: 515}); // failing with message Error: "[object Object] thrown"
  });

如何为函数调用 baz(2) 编写匹配器??

根据文档,您必须将函数的引用提供给 expect,而不是函数的 return 值。

https://jasmine.github.io/api/3.5/matchers.html#toThrow

例子

function error() {
   throw 'ERROR';
}
expect(error).toThrow('ERROR')

对于您的情况,您可以将函数调用包装到另一个函数中。您可以直接在 expect 参数中内联该函数的声明:

expect(() => baz(2)).toThrow({status: 515});
// equivalent with
expect(function(){ baz(2) }).toThrow({status: 515});

另一种方法是使用 .bind 将参数附加到函数而不调用它。

expect(baz.bind(null, 2)).toThrow({status: 515});
//              ^^^^  ^
//           context  first parameter