2012-02-04 85 views
3

我想测试这一功能: /js/lib/front.js我不知道如何用Qunit测试这个?

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不是一个函数

我不明白,我需要在功能测试这样的,以及如何在另一个函数里包含函数?

+0

什么的'this'es指的是在不同的文件吗?你确定你不需要'this.assertInput(“email”)'? – pimvdb 2012-02-04 12:02:21

+0

在第一个代码块中,Form是一个实例还是一个静态引用? – 2012-02-04 12:39:14

+0

我有:function Form(){this.assertInput = function(name,defaultValue){....}} – 2012-02-04 13:25:41

回答

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"); 
    }); 
});