加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

如何解决在AngularJS,Jasmine 2.0的promise,当没有$scope强制摘

发布时间:2020-12-17 08:50:14 所属栏目:安全 来源:网络整理
导读:看起来promises do not resolve in Angular/Jasmine tests unless you force a $scope.$digest() .这是愚蠢的IMO但很好,我有工作在适用(控制器)。 我现在的情况是我有一个服务,可以关心任何范围的应用程序,所有它从服务器返回一些数据,但promise似乎没有
看起来promises do not resolve in Angular/Jasmine tests unless you force a $scope.$digest().这是愚蠢的IMO但很好,我有工作在适用(控制器)。

我现在的情况是我有一个服务,可以关心任何范围的应用程序,所有它从服务器返回一些数据,但promise似乎没有解决。

app.service('myService',function($q) {
  return {
    getSomething: function() {
      var deferred = $q.defer();
      deferred.resolve('test');
      return deferred.promise;
    }
  }
});
describe('Method: getSomething',function() {
  // In this case the expect()s are never executed
  it('should get something',function(done) {
    var promise = myService.getSomething();

    promise.then(function(resp) {
      expect(resp).toBe('test');      
      expect(1).toEqual(2);
    });

    done();
  });

  // This throws an error because done() is never called.
  // Error: Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.
  it('should get something',function(done) {
    var promise = myService.getSomething();

    promise.then(function(resp) {
      expect(resp).toBe('test');      
      expect(1).toEqual(2);
      done();
    });
  });
});

测试此功能的正确方法是什么?

编辑:解决方案参考。显然,你被迫注入和消化$ rootScope,即使服务没有使用它。

it('should get something',function($rootScope,done) {
    var promise = myService.getSomething();

    promise.then(function(resp) {
      expect(resp).toBe('test');      
    });

    $rootScope.$digest();
    done();
  });
您需要在测试中注入$ rootScope并触发$ digest。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读