使用JsTestDriver和Mockjax测试内联回调函数

Testing inline callback function with JsTestDriver and Mockjax

本文关键字:回调 函数 测试 JsTestDriver Mockjax 使用      更新时间:2023-09-26

我想测试以下AJAX函数

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

我应该如何使用JsTestDriver来测试my.var是否已更改?

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

我尝试过使用queue.call方法,但未成功

我找到了以下解决方案

// 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);
    });
});