2014-10-11 131 views
0

我正在做一些使用角度承诺的茉莉花测试,并有一个与时间有关的问题。在这里找到一个答案Unit-test promise-based code in Angular,但需要澄清这是如何工作的。鉴于then方法总是以异步方式处理,下面的测试如何保证通过。是否存在expect会在正在执行的then块之前运行并且在值被分配之前运行期望的风险。或者...摘要循环保证在预期运行之前分配值。意思是说,摘要循环将有效地像阻塞调用一样,保证在代码被允许继续之前所有的承诺都被解决。使用承诺的茉莉花异步测试

function someService(){ 
    var deferred = $q.defer(); 
    deferred.resolve(myObj); 
    return deferred.promise; 
} 

it ('testing promise', function() { 
    var res; 
    var res2; 
    someService().then(function(obj){ 
    res = "test"; 
    }); 

    someService().then(function(obj){ 
    res2 = "test2"; 
    }); 

    $rootScope.$apply(); 
    expect(res).toBe('test'); 
    expect(res2).toBe('test2'); 
}); 

回答

0

虽然米哈尔的答案指向正确的想法,这里的关键是,$apply()是呼吁相关范围。以下是来自Angular文档的示例:

it('should simulate promise', inject(function($q, $rootScope) { 
    var deferred = $q.defer(); 
    var promise = deferred.promise; 
    var resolvedValue; 

    promise.then(function(value) { resolvedValue = value; }); 
    expect(resolvedValue).toBeUndefined(); 

    // Simulate resolving of promise 
    deferred.resolve(123); 
    // Note that the 'then' function does not get called synchronously. 
    // This is because we want the promise API to always be async, whether or not 
    // it got called synchronously or asynchronously. 
    expect(resolvedValue).toBeUndefined(); 

    // Propagate promise resolution to 'then' functions using $apply(). 
    $rootScope.$apply(); 
    expect(resolvedValue).toEqual(123); 
})); 
+0

我不认为这是正确的。根据你调用'$ apply'的范围,行为没有任何区别。然而'$ digest'的行为取决于哪个范围。 – 2014-10-19 14:49:45