Jasmine.js:抛出Error的预期函数,但它抛出了Function

时间:2017-08-23 20:43:00

标签: javascript testing jasmine bdd

我正在尝试使用一个简单的计算器应用程序(可以在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语句不起作用,但它也不喜欢这样。

1 个答案:

答案 0 :(得分:2)

TypeError 是一个功能。您需要在throw时调用它。

 throw new TypeError('some message');

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