在 jasmine 上测试非常简单的异步函数

Test very simple async function on jasmine

我需要测试这个功能,

我看到了各种 post 但我可以让它工作

我也试过 'done' 回调

我也尝试将 $apply 调用放在它之外

测试文件

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

此时您没有等待承诺:

  it('uno', function(){

      asi.tes().then(function(po){
          res = po;    
      });

      root.$digest();
      expect(res).toBe(9);
  });

root.$digest();并期望(res).toBe(9);在 asi.tes() 之后立即被调用。 您可以将您的函数标记为异步并使用 await:

等待承诺
 it('uno', async function(){

      res = await asi.tes();

      root.$digest();
      expect(res).toBe(9);
  });

首先,你应该使用$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