tags:

views:

556

answers:

2

I have the following HTML code:

<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>

And the following Javascript code ( with JQuery as the library):

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

Now, how to test $("#username").click so that for a given input, it

  1. calls the correct url ( in this case, its ViewRecord/GetSoftwareChoice)
  2. And, the output is expected (in this case, function(data)) behaves correctly?

Any idea how to do this with QUnit?

Edit: I read the QUnit examples, but they seem to be dealing with a simple scenario with no AJAX interaction. And although there are ASP.NET MVC examples, but I think they are really testing the output of the server to an AJAX call, i.e., it's still testing the server response, not the AJAX response. What I want is how to test the client side response.

A: 
  1. override $.getJSON in your test to assert the passed in url is correct. if you need to do this a lot, you can create a helper function that overrides getJSON and asserts the url. Make sure to call the default implementation after your assert. Also, after you assert the url, stop() the test.

Wrap the passed in callback with a function that starts the test, and calls the callback.

Start the test.

trigger a click on the #username.

Edit:

This might help: http://stackoverflow.com/questions/941133/qunit-with-ajax-qunit-passes-the-failing-tests

mkoryak
OK, is there anyway to pass back the dummy data?
Ngu Soon Hui
what do you mean 'pass back', where? and what dummy data?
mkoryak
dummy data= the data returns from the server.
Ngu Soon Hui
A: 

You could replace your anonymous event handler with function call and in your tests you could then just invoke that function.

So instead of

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

You could do something like

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

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

And then in your QUnit tests you could just invoke

doSomething();
RaYell