2009-06-16 68 views
4

我有以下的HTML代碼:QUnit單元測試:測試鼠標點擊

<div id="main"> 
    <form Id="search-form" action="/ViewRecord/AllRecord" method="post"> 
    <div> 
     <fieldset> 
      <legend>Search</legend> 
      <p> 
       <label for="username">Staff name</label> 
       <input id="username" name="username" type="text" value="" /> 
       <label for="softype"> software type</label> 

       <input type="submit" value="Search" /> 
      </p> 
     </fieldset> 
    </div> 
    </form> 
</div> 

而且下面的JavaScript代碼(使用jQuery的庫):

$(function() { 
$("#username").click(function() { 
     $.getJSON("ViewRecord/GetSoftwareChoice", {}, 
    function(data) { 
     // use data to manipulate other controls 
    }); 
    }); 
}); 

現在,如何測試$("#username").click因此,對於給定的輸入,它

  1. 調用正確的URL(在這種情況下,它的ViewRecord/GetSoftwareChoice
  2. 而且,預計輸出(在這種情況下,function(data))的行爲是否正確?

任何想法如何做到這一點與QUnit

編輯:我讀了QUnit examples,但他們似乎在處理一個沒有AJAX交互的簡單場景。雖然there are ASP.NET MVC examples,但我認爲他們真的測試服務器的輸出到AJAX調用,即它仍在測試服務器響應,而不是AJAX響應。我想要的是如何測試客戶端響應。

+0

不是很多,我害怕;我真的不知道如何開始。 – Graviton 2009-06-16 15:53:47

回答

0
  1. 重寫$ .getJSON在您的測試中聲明傳入的url是正確的。如果你需要做很多事情,你可以創建一個幫助函數來覆蓋getJSON並聲明url。確保在聲明後調用默認實現。 另外,在斷言url之後,停止()測試。

用啓動測試的函數包裝傳入的回調函數,並調用回調函數。

開始測試。

觸發點擊#username。

編輯:

這可能幫助: QUnit with Ajax, QUnit passes the failing tests

+0

好的,有無論如何要傳回虛擬數據? – Graviton 2009-06-16 15:56:09

+0

你是什麼意思'傳回',在哪裏?以及什麼虛擬數據? – mkoryak 2009-06-16 15:56:51

6

您可以用函數調用,並在您的測試,那麼你可以只調用該函數替換您的匿名事件處理程序。

所以不是

$("#username").click(function() { 
    $.getJSON("ViewRecord/GetSoftwareChoice", {}, function(data) { 
    // use data to manipulate other controls 
    }); 
}); 

你可以做類似

function doSomething() { 
    $.getJSON("ViewRecord/GetSoftwareChoice", {}, function(data) { 
    // use data to manipulate other controls 
    }); 
} 

$("#username").click(doSomething); 

,然後在QUnit的測試,你可以只調用

doSomething(); 
0

你並不總是想取得真正的阿賈克斯電話。在這種情況下,mockjax是一個很好的解決方案。 您可以在測試中分配一個返回值。因此,您將能夠請求信息而無需執行或其他文件。

在你的情況下,它可以是這樣的:

$.mockjax({ 
    url: '/ViewRecord/GetSoftwareChoice', 
    responseTime: 750, 
    responseText: { 
    status: 'success', 
    result: 'your data can be put here' //in that case it is data.result with value string 
    } 
}); 

你可以測試Ajax調用的請求,您可以測試點擊就可以測試其他行爲。

Ps。你用結果「覆蓋」ajax調用。 Ps2。 Mockjax可以在這裏找到:https://github.com/appendto/jquery-mockjax