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

angularjs – Angular&Jasmine:如何测试$q promise链是否已

发布时间:2020-12-17 16:56:47 所属栏目:安全 来源:网络整理
导读:我有一个服务,它公开一个函数,它接收一个解析的CSV(使用 papaparse)和一个反映解析状态的promise: ?如果文件缺少必填字段,则拒绝承诺 ?否则,它会将每行解析为一个项目并自动填充缺少的字段(自动填充过程是异步的). ?填充所有项目时,该函数使用items数组解析
我有一个服务,它公开一个函数,它接收一个解析的CSV(使用 papaparse)和一个反映解析状态的promise:
?如果文件缺少必填字段,则拒绝承诺
?否则,它会将每行解析为一个项目并自动填充缺少的字段(自动填充过程是异步的).
?填充所有项目时,该函数使用items数组解析promise

我要测试的函数是onCsvParse:

angular.module('csvParser',[])
  .factory('csvParser',['$http',function($http) {
      var service = {
        onCsvParse: function(results,creatingBulkItems) {
          var errors = this.getCsvErrors(results);
          if (errors.length > 0) {
            //reject
            creatingBulkItems.reject(errors);
          } else {

            var items = this.parseCsv(results);
            var autoPopulateItems = [],populatedItems = [];
            for (var i = 0; i < populatedItems.length; i++) {
              var item = items[i];
              if (item.name === "" /*or some any field is missing */ ) {
                // auto populate item
                autoPopulateItems.push(this.autoPopulateItem(item));
              } else {
                var populatedItem = $q.when(item);
                populatedItems.push(populatedItem);
              }
            }
            populatedItems =autoPopulateItems.concat(populatedItems);
            var populatingAllItems = $q.all(populatedItems);
            populatingAllItems.then(function(items) {
              creatingBulkItems.resolve(items);
            },function(err) {
              creatingBulkItems.resolve(err);
            });
          }
        },autoPopulateItem: function(newItem) {
          var populatingItem = $q.defer();
          var item = angular.copy(newItem);
          $http.post('api/getItemData',{ /*.....*/ })
            .success(function(response) {
              //----Populate item fields
              item.name = response.name;
              //....
              //resolve the promise
              populatingItem.resolve(item)

            }).error(err) {
              // resolving on error for $q.all indication
              populatingItem.resolve(item)
            };
          return populatingItem.promise;

        }
      }
      return service;
    }
  ])

我对此方法的测试如下(简化):

describe('bulk items upload test',function() {
  //upload csv & test scenarios...
  var $rootScope,$q,csvResults = {};
  var $httpBackend,requestHandler;
  beforeEach(module('csvParser'));

  beforeEach(inject(function(_$rootScope_,_$q_) {
    $rootScope = _$rootScope_;
    $q = _$q_;
  }));
  beforeEach(inject(function($injector) {
    // Set up the mock http service responses
    $httpBackend = $injector.get('$httpBackend');
    // backend definition common for all tests
    requestHandler = $httpBackend.when('POST','api/getItemData')
      .respond({
        name: "name",description: "description",imageUrl: "www.google.com"

      });


    //   afterEach(function(){ $rootScope.$apply();});

  }));
  it('Should parse csv string',function(done) {
    var csvString = "Name,Description of the page";//...

    Papa.parse(csvString,{
      complete: function(results) {
        csvResults = results;
        done();
      }
    });

  });
  it('Should fail',function(done) {
    var creatingBulkItems = $q.defer();
    console.log("here..");
    csvParser.onCsvParse(csvResults,creatingBulkItems);
    creatingBulkItems.promise.then(function() {
      console.log("1here..");
      //promise is never resolved
      expect(1).toEqual(1);
      done();
    },function() {
      //promise is never rejeceted
      console.log("2here..");
      expect(1).toEqual(1);
      done();
    });
    $rootScope.$apply();

  });

});

有了这个,我得到错误:错误:超时 – 在jasmine.DEFAULT_TIMEOUT_INTERVAL指定的超时内没有调用异步回调.

承诺没有解决,虽然我调用了$rootScope.$apply()而且我也没有调用真正的异步调用(只有mocks,除了$q.all).
我怎样才能使它工作?

解决方法

无效的语法.您需要将函数传递给错误回调.

}).error(function(err) {
          // resolving on error for $q.all indication
          populatingItem.resolve(item)
        });
      return populatingItem.promise;

另外,jasime测试需要更多初始化:
http://plnkr.co/edit/wjykvpwtRA0kBBh3LcX3?p=preview

(编辑:李大同)

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

    推荐文章
      热点阅读