使用promises的Jasmine异步测试

时间:2014-10-11 04:56:44

标签: javascript angularjs unit-testing jasmine

我正在使用角度承诺进行一些茉莉花测试,并且有一个与时间有关的问题。在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');
});

2 个答案:

答案 0 :(得分:1)

  

摘要周期将有效地表现为阻塞调用,保证在允许代码继续执行之前解析所有承诺。

是的,虽然更准确,但它可以保证已解决的承诺的成功回调将会运行。

有一个非常相似的example that shows how the digest cycle is tied to the success callbacks of promises in the docs for $q

答案 1 :(得分:0)

虽然Michal的回答指出了正确的想法,但这里的关键是在相关范围内调用$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);
}));