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

angularjs – 如何解决$q.all承诺在Jasmine单元测试?

发布时间:2020-12-17 08:31:26 所属栏目:安全 来源:网络整理
导读:我的控制器有如下代码: $q.all([qService.getData($scope.id),dService.getData(),qTService.get()]).then(function (allData) { $scope.data1 = allData[0]; $scope.data2 = allData[1]; $scope.data3 = allData[2];}); 在我的单元测试中,我做这样的事情
我的控制器有如下代码:
$q.all([qService.getData($scope.id),dService.getData(),qTService.get()])
.then(function (allData) {
  $scope.data1 = allData[0];
  $scope.data2 = allData[1];
  $scope.data3 = allData[2];
});

在我的单元测试中,我做这样的事情:

beforeEach(inject(function($rootScope,$q,$location){// and other dependencies... 
  qServiceSpy = spyOn(_qService,'getData').andCallFake(function () {
    var data1 = {
      id: 1,sellingProperty: 1,};
    var d = $q.defer();
    d.resolve(data1);
    return d.promise;
  });

  dServiceSpy = spyOn(_dService,'getData').andCallFake(function () {
    var data2 = [{ "id": "1","anotherProp": 123 }];
    var d = $q.defer();
    d.resolve(data2);
    return d.promise;
  });
  qTServiceSpy = spyOn(_qTService,'get').andCallFake(function () {
    var data3 = [{ id: 0,name: 'Rahul' }];
    var d = $q.defer();
    d.resolve(data3);
    return d.promise;
  });
  rootScope = $rootScope;
});

现在在我的测试中,我检查如果服务被调用,data1,data2不是未定义。

it('check if qService' got called,function() {
  expect(scope.data1).toBeUndefined();
  rootScope.$digest();
  expect(_quoteService.getQuote).toHaveBeenCalled();
});
it('check if "data1" is defined',function () {
  expect(scope.data1).toBeUndefined();
  rootScope.$digest();
  expect(scope.data1).toBeDefined();
});

我的问题是,这是工作正常,直到我替换我的个人服务调用在控制器与q.all和在测试范围。$ apply与rootScope。使用q.all和rootScope。$ digest(尝试使用范围$ apply)以及两个测试失败,错误:

10 $digest() iterations reached. Aborting!

如果我删除rootScope。$ digest然后promises从来没有得到解决和测试失败说

expected undefined to be defined.

任何帮助我应该如何单元测试代码与q.all?

遇到了this post

但这也没有帮助,因为我已经尝试使用$ digest。

您可以尝试将$ rootScope。$ apply()放在afterEach()回调函数中。 Promises在$ apply()中解析。
afterEach(function(){
    rootScope.$apply();
});

(编辑:李大同)

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

    推荐文章
      热点阅读