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

时间:2018-04-02 15:12:50

标签: angularjs jasmine karma-jasmine angular-promise

我需要测试这个功能,

我看到各种帖子,但我可以使它有效

我尝试过'完成'回调也是

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

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

2 个答案:

答案 0 :(得分:1)

此时你并没有等待承诺:

  it('uno', function(){

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

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

根$消化();并期望(res).toBe(9);在asi.tes()之后立即调用。 您可以将函数标记为异步并等待承诺:

 it('uno', async function(){

      res = await asi.tes();

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

答案 1 :(得分:1)

首先,您应该使用color angularjs服务而不是setTimeout。

您可以使用$timeout

测试您的代码,如下所示
$timeout.flush();

});

以下是工作示例:$timeout async test in angularjs