Javascript Jasmine.js:期望函数抛出错误,但它抛出了函数
我试图习惯用Jasmine编写单元测试(一般来说)和一个简单的计算器应用程序(您可以在中看到) 我想确定的一件事是,如果你把一个字符串传递到计算器中,就会抛出一个TypeError。为此,我在函数中编写了以下代码:Javascript Jasmine.js:期望函数抛出错误,但它抛出了函数,javascript,testing,jasmine,bdd,Javascript,Testing,Jasmine,Bdd,我试图习惯用Jasmine编写单元测试(一般来说)和一个简单的计算器应用程序(您可以在中看到) 我想确定的一件事是,如果你把一个字符串传递到计算器中,就会抛出一个TypeError。为此,我在函数中编写了以下代码: Calculator.prototype.addition = function (num1, num2) { if (isNaN(num1) || isNaN(num2)) { throw TypeError; } return num1 + num2; };
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.
➜ 计算器吉特:(硕士)✗ npm试验
> calculator@1.0.0测试/用户/某人/工作区/小型项目/计算器
>茉莉花
起动
…F*。。。。。
失败:
1) 如果加法方法有一个字符串,计算器应该抛出一个类型错误
信息:
期望函数抛出错误,但它抛出了函数。
堆栈:
错误:预期函数将抛出错误,但它抛出了函数。
在UserContext。(/Users/somedude/Workspace/small_projects/calculator/spec/calculator/CalcSpec.js:22:53)
悬而未决的:
1) 如果加法方法有两个字符串,计算器应该抛出一个类型错误
暂时禁用xit
11个规格,1个故障,1个待定规格
在0.015秒内完成
npm错误!测试失败。请参见上文了解更多详细信息。
这让我感到困惑。如果我不以匿名函数的形式传入函数调用,
expect
语句将不起作用,但它也不象这样 TypeError
是一个函数。您需要在抛出它时调用它
throw new TypeError('some message');
更多信息:
TypeError
是一个函数。您需要在抛出它时调用它
throw new TypeError('some message');
详情如下: