使用Jack的Ajax单元测试模拟

Nic*_*ilt 5 javascript unit-testing qunit

我使用Jack作为JavaScript模拟库.http://github.com/keronsen/jack.我也在使用qunit.

我在我的javascript代码中跟随AJAX调用,我正在编写测试.

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

以下代码正在运行.

jack(function() {
    jack.expect('$.ajax').exactly('1 time');
}
Run Code Online (Sandbox Code Playgroud)

但是,我想测试是否所有参数都已正确提交.我试过以下但没有奏效.

jack.expect('$.ajax').exactly('1 time').whereArgument(0).is(function(){
Run Code Online (Sandbox Code Playgroud)

var args = arguments; ok(' http:// localhost:3000/users ',args.url,'url应该有效'); //对象的许多键的类似测试});

我想得到一些论据,以便我可以进行一系列测试.

ker*_*sen 4

两种方法:

使用.hasProperties():

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

...或者捕获参数并做出 qunit 断言:

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

第一个版本使用了更多的 Jack API(值得更好的文档),并且更具可读性,IMO。

后一个版本将为您提供更好的错误报告。