Ajax unit testing mocking using Jack
javascript, qunit, unit-testing
Solution
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.
Problem
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.