【问题标题】:How to test throw new error JavaScript如何测试抛出新的错误 JavaScript
【发布时间】: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


【解决方案1】:

如果您要测试错误,则需要使用 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-08-15
    • 2019-07-12
    • 1970-01-01
    • 2021-04-03
    • 2016-07-13
    • 1970-01-01
    • 2020-02-26
    相关资源
    最近更新 更多