我正在尝试编写单元测试。如果函数得到负数,它将引发新的错误。
Obj = function () {
};
Obj.prototype.Count = function (number) {
if (number < 0) {
throw new Error("There is no function for negative numbers");
} else...
我的单元测试功能:
function test(then,expected) {
results.total++;
var m1=new Obj();
if (m1.Count(then)!=expected){
results.bad++;
alert(m1.Count(then)+" not equal "+expected);
}
}
var results = {
total: 0,
bad: 0
};
然后我正在尝试运行测试
test(5,120)
test(-5, "There is no function for negative numbers");
第一个可以正常工作,但是我不知道对负数写什么到“expected”。该示例不起作用。
你能告诉我吗?
谢谢!
最佳答案
如果要测试错误,则需要使用try ... catch。
var Obj = function() {};
Obj.prototype.count = function(num) {
if (num < 0) throw new Error("Invalid Number");
else return 0;
}
function test(value, expected) {
results.total++;
var obj = new Obj();
try {
obj.count(value);
}
catch (err) {
if (err.message != expected) results.bad++;
}
}
接着:
test(-5, 'Invalid Number'); // doesn't add one to results.bad
关于javascript - 如何测试抛出新的错误JavaScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30427823/