AngularJS $ q.defer()与jasmine done():promise.then函数未被调用

时间:2016-08-03 22:54:33

标签: angularjs asynchronous jasmine

有人可以帮助我理解为什么这不起作用?我正在使用Jasmine的both函数来等待promise.then函数也被调用并进行断言。但它在被召唤之前就会超时。

describe('greeting', function(){
    var greeting = 'hello';

    it('should call promise.then', function(done) {
        inject(function ($q) {
            var deferred = $q.defer();
            deferred.resolve(greeting);

            deferred.promise.then(function (greeting) {
                expect(greeting).toEqual('hello');
                done();
            });

        });
    });
});

then函数未被调用,Jasmine因此消息超时:

Error: Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.

1 个答案:

答案 0 :(得分:1)

确保执行$scope.$apply以触发角度摘要周期,如下所示:

inject(function ($q, $rootScope) {
   var deferred = $q.defer();
   deferred.resolve(greeting);

   deferred.promise.then(function (greeting) {
      expect(greeting).toEqual('hello');
      done();
   });
   $rootScope.$apply();
});

应解决问题