在茉莉花上测试非常简单的异步功能



我需要测试此功能,

我看到了各种帖子,但我可以使它起作用

我也尝试了"完成"回调

我尝试将$ apply拨打放在IT之外

testfile

describe('description', function() {
  var asi;
  var root;
  var res;
  beforeEach(module('moduloPrueba'));
  beforeEach(inject(function (asincronico, $rootScope) {
           asi = asincronico;
           root = $rootScope;
       })
  );

  it('uno', function(){
      asi.tes().then(function(po){
          res = po;    
      });
      root.$digest();
      expect(res).toBe(9);
  });
});

服务

angular.module('moduloPrueba', [])
  .factory('asincronico', function($q) {
  return {
    tes:tes,
  };
  function tes(){
    var deferred = $q.defer();
    setTimeout(function () {
      deferred.resolve(9);
    }, 500);
    return deferred.promise;
  }
});

首先,您应该使用 $timeout angularjs服务而不是settimeout。

您可以使用$timeout.flush();

来测试您的代码
it('uno', function(){
  asi.tes().then(function(po){
      res = po;    
  });
  $timeout.flush();
  $timeout.verifyNoPendingTasks();
  root.$digest();
  expect(res).toBe(9);

}(;

这是一个工作示例:$ timeout async test in angularjs

此时您不等待承诺:

  it('uno', function(){
      asi.tes().then(function(po){
          res = po;    
      });
      root.$digest();
      expect(res).toBe(9);
  });

root。$ digest((;并期望(res(.tobe(9(;在asi.tes((之后立即调用。您可以将功能标记为异步,并等待应许:

 it('uno', async function(){
      res = await asi.tes();
      root.$digest();
      expect(res).toBe(9);
  });

最新更新