在角度工厂中测试异步功能

时间:2014-08-05 10:33:55

标签: angularjs asynchronous promise factory

我是测试的新手,我试图在Jasmine中测试我的角度代码。我坚持从解决的承诺测试答案的问题。现在测试得到了超时。我想让测试等待响应而不是仅仅放入一个模型响应。我怎么做?这是进行单元测试的一种不好的方法吗?

angular.module("Module1", ['ng']).factory("Factory1", function($q){
    function fn1(){
        var deferred = $q.defer();
        setTimeout(function(){ deferred.resolve(11); }, 100); // this is representing an async action
        return deferred.promise;
    }
    return { func1 : fn1 };
});

describe('test promise from factory', function() {
    var factory1, $rootScope, $q;
    beforeEach(module('Module1'));
    beforeEach(inject(function(Factory1, _$rootScope_, _$q_) {
        factory1=Factory1;
        $rootScope = _$rootScope_;
        $q = _$q_;
    }));

    it('should be get the value from the resolved promise', function(done) {
        factory1.func1().then(function(res){
            expect(res).toBe(11);
            done(); // test is over
        });

        $rootScope.$digest();
    });
});

setTimeout()块表示异步函数调用,我不想用$ timeout替换它。

1 个答案:

答案 0 :(得分:0)

我不知道您为什么不想使用$timeout服务。

但如果您真的想使用setTimeout,则回调中需要$rootScope.$digest()

function fn1() {
  var deferred = $q.defer();

  // this is representing an async action
  setTimeout(function() {
    deferred.resolve(11);
    $rootScope.$digest(); // this is required ($timeout do this automatically).
  }, 100); 

  return deferred.promise;
}
相关问题