是否可以使用D.O.H测试一系列异步函数调用

时间:2009-06-17 13:51:03

标签: javascript testing dojo doh

我正在尝试使用doh.Deferred来编写一个检查以下事件序列的测试:

  1. 使用用户A(异步)
  2. 登录
  3. 退出(同步)
  4. 使用用户A(异步)
  5. 登录

    第二个回调函数的返回值是另一个doh.Deferred对象。我的印象是d的回调链会等待d2,但事实并非如此。测试在调用d2.callback之前完成。

    我在哪里错了?

    有没有人知道我测试这种行为的更好方法?

    function test() {
        var d = new doh.Deferred();
    
        d.addCallback(function() {  
            Comm.logout(); /* synchronus */
            try {   
                // check with doh.t and doh.is
                return true;
            } catch (e) {
                d.errback(e);
            }
        });
    
        d.addCallback(function() {
            var d2 = new dojo.Deferred();
            /* asynchronus - third parameter is a callback */
            Comm.login('alex', 'asdf', function(result, msg) {
                    try {
                        // check with doh.t and doh.is
                        d2.callback(true);
                    } catch (e) {
                        d2.errback(e);
                    }                   
                });
            return d2; // returning doh.Defferred -- expect d to wait for d2.callback
        });     
    
        /* asynchronus - third parameter is a callback */
        Comm.login('larry', '123', function (result, msg) {
            try {
                // check with doh.t and doh.is 
                d.callback(true);
            } catch (e) {
                d.errback(e);
            }
        }); 
    
        return d;
    }
    

1 个答案:

答案 0 :(得分:0)

这很有效。 d2的范围是问题。

function test() {
    var d = new doh.Deferred();
    var d2 = new doh.Deferred();

    d.addCallback(function() {  
        Comm.logout(); /* synchronus */
        try {   
                // check with doh.t and doh.is
                return true;
        } catch (e) {
                d.errback(e);
        }
    });

    d.addCallback(function() {
        /* asynchronus - third parameter is a callback */
        Comm.login('alex', 'asdf', function(result, msg) {
                        try {
                                // check with doh.t and doh.is
                                d2.callback(true);
                        } catch (e) {
                                d2.errback(e);
                        }                                       
                });
        return d2; // returning doh.Deferred -- waits for d2.callback
    });         

    /* asynchronus - third parameter is a callback */
    Comm.login('larry', '123', function (result, msg) {
        try {
                // check with doh.t and doh.is 
                d.callback(true);
        } catch (e) {
                d.errback(e);
        }
    }); 

    return d;
}
相关问题