2012-02-04 88 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"); 
    }); 
});