【问题标题】:Testing Angular when mixing $q and ES6 promises在混合 $q 和 ES6 Promise 时测试 Angular
【发布时间】:2015-11-27 22:17:08
【问题描述】:

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

这段代码 sn-p 演示了 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

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

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

最后,请注意,在控制器中,我演示了两个 FAILING 测试实际上在生产环境中起作用。

为什么 Angular 不允许我在测试中混合使用 ES6 和 $q Promise,但在生产代码中却没有问题?

【问题讨论】:

  • 您是否尝试从问题开始?也许这是一个错误,您设计了一种非常简单的方法来重现它。

标签: javascript angularjs jasmine angular-promise es6-promise


【解决方案1】:

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

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

【讨论】:

  • 这对我有用,但我在 Jasmine 上创建了这个问题,希望他们能创建一个适当的修复程序:github.com/jasmine/jasmine/issues/1200
  • @yukw777 不要忘记在 afterEach 函数中将其恢复为原始值。否则其他测试可能会因为 $q 在不同的角度上下文中创建而失败。
猜你喜欢
  • 2016-07-15
  • 1970-01-01
  • 2019-05-31
  • 2016-05-26
  • 1970-01-01
  • 1970-01-01
  • 2015-10-21
  • 2021-01-22
  • 1970-01-01
相关资源
最近更新 更多