Jasmine.js: 预期函数抛出错误,但它抛出了函数

Jasmine.js: Expected function to throw an Error, but it threw Function

我正在尝试使用简单的计算器应用程序(您可以在 my Github 看到)在 Jasmine 中(以及一般情况下)编写单元测试。

我想确定的一件事是,如果您将字符串传递给计算器,则会抛出 TypeError。为此,我在函数中写入了以下代码:

Calculator.prototype.addition = function (num1, num2) {
  if (isNaN(num1) || isNaN(num2)) {
    throw TypeError;
  }
  return num1 + num2;
};

和下面的测试代码:

var Calculator = require('../../lib/calculator/Calculator');

describe("Calculator", function () {

  let calc = new Calculator();
  var num1 = 2;
  var num2 = 2;

it("should throw a type error if the addition method is given one string", function() {
    expect(function() {calc.addition('lol', num2)}).toThrowError(TypeError);
  });

尝试使用此代码进行 运行 测试会得到以下输出:

➜  calculator git:(master) ✗ npm test

> calculator@1.0.0 test /Users/somedude/Workspace/small_projects/calculator
> jasmine

Started
....F*.....

Failures:
1) Calculator should throw a type error if the addition method is given one string
  Message:
    Expected function to throw an Error, but it threw Function.
  Stack:
    Error: Expected function to throw an Error, but it threw Function.
        at UserContext.<anonymous> (/Users/somedude/Workspace/small_projects/calculator/spec/calculator/CalcSpec.js:22:53)
Pending:

1) Calculator should throw a type error if the addition method is given two strings
  Temporarily disabled with xit

11 specs, 1 failure, 1 pending spec
Finished in 0.015 seconds

npm ERR! Test failed.  See above for more details.

这让我很困惑。如果我不将函数调用作为匿名函数传递,expect 语句将不起作用,但它也不喜欢这样。

TypeError 一个函数。你需要在 throw 的时候调用它。

 throw new TypeError('some message');

更多信息:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypeError