javascript - 如何测试抛出新的错误JavaScript

标签 javascript unit-testing error-handling throw

我正在尝试编写单元测试。如果函数得到负数,它将引发新的错误。

   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/

相关文章:

javascript - 事件处理程序,损坏的页面

javascript - jquery将脚本动态附加到html元素

unit-testing - 何时以及为什么应该编写参数化的 JUnit 测试用例?

java - 启动MiniDFSCluster时出错

python - Python中的自定义异常似乎不遵循 "its easier to ask for forgiveness"?

Python GAE : How to return JSON-formated response even when an error occurs?

javascript - 如何使用react调用外部定义的javascript函数?

javascript - 如何在加载 jQuery 时使用 SVGweb 嵌入 SVG(即问题)

unit-testing - 可重用的模拟与每个测试中的模拟

django - 无法通过生产中的邮件拦截404错误(debug = False)