Question

I want to test the following AJAX function

my.var = true;
my.method = function() {
    $.getJSON('/path/to/', 
        function(data){
                my.var = false;
});
}

How should I use JsTestDriver to test that my.var has changed?

AsyncTestCase("MyAsyncTestCase", {

    $.mockjax({
        url: '/path/to/'
    });
    my.method();
});

I've tried to use queue.call method unseccessfully

Was it helpful?

Solution

I found the following solution

// your code
my.var = true;
my.method = function() {
     return = $.getJSON('/path/to/', 
                  function(data){
                      my.var = false;
              });
}

// test
AsyncTestCase("MyAsyncTestCase", {

    $.mockjax({
        url: '/path/to/',
        responseTime: 100,
        responseText: {
            result: true
        }
    });

    queue.call('Step1: send request and expect a callback', function(callbacks){

        var onComplete = callbacks.add(function(response){
                //console.debug(response);
        });

        // call method
        var jqXHR = my.method();

        jqXHR.complete(function(){
            onComplete(jqXHR.responseText);
        });
    });

    queue.call('Step 2: after ajax call, make assertions', function(){
        // assert variable is false
        assertFalse(my.var);
    });
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top