【发布时间】:2015-08-06 07:31:45
【问题描述】:
我正在尝试编写单元测试。如果函数得到负数,它会抛出新的错误。
Obj = function () {
};
Obj.prototype.Count = function (number) {
if (number < 0) {
throw new Error("There is no function for negative numbers");
} else...
我的unit-tet函数:
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");
第一个工作正常,但我不知道要写什么给负数的“预期”。该示例不起作用。 请给我建议好吗?
谢谢!
【问题讨论】:
-
这是一种通常称为预期异常的测试。您想编写自己的 JS 测试框架吗?或者你想测试你的代码?因为如果是第二个 - 那里有很多现成的 JS 测试框架。
-
我只是想测试我的代码。
-
那么我建议选择现有的框架,例如这个,它有检查异常api.qunitjs.com/throws
-
您必须捕获异常,负数的预期结果将是特定异常。
-
@jfriend00 我应该使用 try 和 catch 吗?所以我必须为负数和正数做不同的测试函数?
标签: javascript unit-testing error-handling throw