【发布时间】: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