我不知道如何用Qunit测试这个?

时间:2012-02-04 11:48:34

标签: javascript jquery qunit

我想测试这个功能: /js/lib/front.js

var Front = function(){
  this.onSignUp = function(){
    if (!Form.assertInput("email")) {
        $("input[name=email]").focus();

        this.showHiddenMessage("Email not set.");

        return false;
    }
 }

}

我有: /js/lib/form.js

function Form() {
     this.assertInput = function (name, defaultValue) {
    var text = $("input[name=" + name + "]").val();

    if (defaultValue != null) {
        if (defaultValue && text == defaultValue) 
            return false;
    }


    if(this.trim(text)) return true;

    return false;
}
}

这个简单的测试通过:

test("Front", function() {
    var front = new Front()
    ok(front);

 });

但如果我写这样的话:

test("On Sign Up ", function() {
    var front = new Front()

    equal(front.onSignUp(),false,"passing test");

 });

我有错误: 死于测试#1:Form.assertInput不是函数

我不明白,我需要在这个函数中测试什么以及如何在另一个函数中包含函数?

1 个答案:

答案 0 :(得分:2)

我保存了一个工作小提琴here。作为旁注,您可能想查看有关使用qUnit here的教程。您需要注意的一件事是当您声明您的功能时。它说Form.assertInput不是函数,因为你无法像这样访问它。您需要使用this关键字,该关键字引用当前上下文。代码应该是这样的:

var Form = function () {
    //good to have assertInput first if you're using it in a later function
    this.assertInput = function (name, defaultValue) {
        var text = $("input[name=" + name + "]").val();

        if (defaultValue != null) {
            //safer to explicitly close your if statements with {}
            if (defaultValue && text == defaultValue) {
               return false;
            }
        }

        if ($.trim(text)) { return true; }

        return false;
    };

    this.showHiddenMessage = function (message) {
        alert(message);
    };

    this.onSignUp = function() {
        //this will point to the current context, in this case it will be Form class
        if (!this.assertInput("email")) {
            $("input[name=email]").focus();

            this.showHiddenMessage("Email not set.");

            return false;
        }
    };
};

同样在您给出的示例代码中,您错过了Front类。所以我在我的小提琴中创建了一个虚拟的:

var Front = function() {};

以下是运行的测试:

$(document).ready(function() {
    test("Front", function() {
        var front = new Front();
        ok(front);

    });
    test("On Sign Up ", function() {
       var form = new Form();
       equal(form.onSignUp(), false, "passing test");
    });
});