我遇到一个问题,我的代码混合了 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
请注意,前 2 个测试通过了,因为它们是简单的 ES6 或 $q promise 。
然后注意所有其他测试都失败了,因为我以不同的方式混合了 ES6 和 $q promises。
最后,请注意我在 Controller 中演示了两个 FAILING 测试实际上在生产中起作用。
为什么 Angular 不允许我在测试中混合使用 ES6 和 $q promise,但在生产代码中却没有问题?
最佳答案
我的单元测试也遇到了这个问题。在我对问题做出解释并找到合适的解决方案之前,我会使用一种解决方法:
if (window.Promise !== $q) {
window.Promise = $q;
}
关于javascript - 混合 $q 和 ES6 promise 时测试 Angular,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33965435/