views:

152

answers:

1

I am using Jack as JavaScript mocking library. http://github.com/keronsen/jack . I am also using qunit.

I have following AJAX call in my javascript code which I am tring to write test for.

$.ajax({
    url: $('#advance_search_form').attr('action'),
    type: 'post',
    dataType: 'json',
    data: parameterizedData,
    success: function(json) {
        APP.actOnResult.successCallback(json);
    }
});

Following code is working.

jack(function() {
    jack.expect('$.ajax').exactly('1 time');
}

However I want to test if all the arguments are properly submitted. I tried following but did not work.

jack.expect('$.ajax').exactly('1 time').whereArgument(0).is(function(){

var args = arguments; ok('http://localhost:3000/users', args.url, 'url should be valid'); // similary test for many keys of object });

I want to get hold of arguments so that I could perform a battery of test.

+2  A: 

Two approaches:

Use .hasProperties():

jack.expect('$.ajax').once()
    .whereArgument(0).hasProperties({
         'type': 'post',
         'url': 'http://localhost:3000/users'
    });

... or capture the arguments and make qunit assertions:

var ajaxArgs;
jack.expect('$.ajax').once().mock(function() { ajaxArgs = arguments[0]; });
// ... the code that triggers .ajax()
equals('http://localhost:3000/users', ajaxArgs.url);

The first version uses more of the Jack API (that deserves better documentation), and is more readable, IMO.

The latter version will give you much better error reporting.

keronsen
awesome. Thanks for the quick look.
Nadal
Take two minutes to add both the approaches to README of jack. once again good job with jack. I love it.
Nadal
first approach is working. Second approach is failing. Both arguments and arguments[0] are reporting as undefined.
Nadal
Strange. Try replacing the function part with function(a) { ajaxArgs = a; }
keronsen
Yeap that did it. passing a to the function solved the problem. Thanks a bunch.
Nadal