混合$q和ES6时测试Angular承诺

Testing Angular when mixing $q and ES6 promises

本文关键字:测试 Angular 承诺 ES6 混合      更新时间:2023-09-26

我遇到了一个问题,我的代码将ES6-Promises与Angular Promises混合在一起,并且它在生产中工作,因为我无法编写通过的单元测试。

这个代码片段演示了Jasmine单元测试将失败,但代码在生产中运行良好的两个实例:

  // An angular $q promise
  var f1 = function() {
    return $q(function(resolve, reject) {
      resolve('This is function 1!');
    });
  }
  // An ES6 promise
  var f2 = function() {
    return new Promise(function(resolve, reject) {
      resolve('This is function 2!');
    });
  }
  // An angular $q.all() promise, attempting to resolve a $q and ES6 promise.
  var s1 = function() {
    return $q.all([f1(), f2()]).then(function() {
      return '$q resolved both promises!'
    });
  }
  // An ES6 promise attempting to resolve a $q and an ES6 promise.
  var s2 = function() {
    return Promise.all([f1(), f2()]).then(function() {
      return 'ES6 resolved both promises!'
    });
  }

测试看起来像:

describe('Testing mixed ES6 promises and Angular $q', function() {
  var $scope = null;
  var service = null;
  //you need to indicate your module in a test
  beforeEach(module('plunker'));
  beforeEach(inject(function($rootScope, _testService_) {
    $scope = $rootScope.$new();
    service = _testService_;
  }));
  afterEach(function() {
  });
  it('should resolve f1', function(done) {
    var t1 = service.f1();
    t1.then(function() {
      done();
    });
    $scope.$apply();
  });
  it('should resolve f2', function(done) {
    var t1 = service.f1();
    t1.then(function() {
      done();
    });
    $scope.$apply();
  });
  it('should resolve s1', function(done) {
    var t1 = service.s1();
    t1.then(function() {
      done();
    });
    $scope.$apply();
  });
  it('should resolve s2', function(done) {
    var t1 = service.s2();
    t1.then(function() {
      done();
    });
    $scope.$apply();
  });
});

这个Plunker有一个工作演示:http://plnkr.co/edit/xhRc7O

请注意,前两个测试通过了,因为它们是简单的ES6或$q承诺。

然后注意到,其他所有测试都失败了,因为我以不同的方式混合了ES6和$q承诺。

最后,请注意,在控制器中,我演示了两个FAILING测试在生产中确实有效。

为什么Angular不让我在测试中混合ES6和$q承诺,但在生产代码中却没有问题?

我在单元测试中也遇到了这个问题。在我对这个问题做出解释并找到合适的解决方案之前,我会使用一个变通方法:

    if (window.Promise !== $q) {
        window.Promise = $q;
    }