1

working ajax call code is given below

$('#callControllerBtn').click(function () {
    currentlySelectedRow = grid.select();
    sendProductIDToController(currentlySelectedRow);
});

function sendProductIDToController(currentlySelectedRow) {
    $.ajax({
        url: "Home/sendProductID/", // Home = Controller , sendProductID = Action
        data: {
            ID: pID
        },
        cache: false,
        type: "POST",
        timeout: 10000,
        dataType: "json",
        success: function (result) {
            if (result) {
                alert("Successfully Completed");
                grid.removeRow(currentlySelectedRow);
                editor.value("");
            } else {
                alert("Failed");
            }
        }
    });
}

Now i want to write the same code but using JS test method.I am using QUnit, ChutzPah in vs 2010, just let me what is the good practice to mock/Fake ajax call also implement working code with test method.

Gurpreet Singh
  • 20,907
  • 5
  • 44
  • 60
Shantu
  • 77
  • 9

2 Answers2

1

http://net.tutsplus.com/tutorials/javascript-ajax/how-to-test-your-javascript-code-with-qunit/

Check out the async chapters.

You can use the JQuery fixture property in your $.ajax() object literal argument to specify a static file which your ajax call should be re-routed to. Here's a good explanation of fixtures in the JMVC documentation:

http://javascriptmvc.com/docs.html#!jQuery.fixture

HankHendrix
  • 295
  • 2
  • 9
  • I really appreciate this tutorial, but what about the mock or fake ajax call, i mean instead of really calling a server page how can i make it fake call ? Any Idea ? – Shantu Jan 29 '13 at 18:49
  • I might be wrong here but I think you can use a fixture for your ajax calls. It acts as sample data for the test. – HankHendrix Jan 29 '13 at 22:38
0

I know this question is old but I've had the same problem and this is the way I fixed it:

I hijacked the $.ajax function to not do the call:

var $.ajaxResults = [];

$.ajax = function(options) {
    $.ajaxResults.push(options);
}

you will probably need some more complicated code here, depending on the case, to catch all parameters or whatever. But in my application I always use $.ajax(options)

then, in the test you can do this:

// the code below initializes the control and triggers an ajax call
$('#ddTest').dropdown();

// check if the ajax call was triggered
equal($.ajaxResults.length, 1, "there is one registered ajax call");

// ajax callback -> run the callback with fake data to populate the control
$.ajaxResults[0].success([
    { value: '1', label: 'one' },
    { value: '2', label: 'two' },
    { value: '3', label: 'three' }
]);

this way you can check both the call parameters and the callback functions

Alex Popescu
  • 71
  • 1
  • 8