cru*_*nch 7 javascript jasmine angularjs es6-promise angular-promise
我遇到的问题是我的代码将ES6 Promises与Angular承诺混合在一起,并且它在生产中起作用,我无法编写通过的单元测试.
此代码段演示了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!'
});
}
Run Code Online (Sandbox Code Playgroud)
测试看起来像:
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();
});
});
Run Code Online (Sandbox Code Playgroud)
这个Plunker有一个工作演示:http://plnkr.co/edit/xhRc7O
请注意,前两个测试通过,因为它们是直接的ES6或$ q承诺.
然后注意每个其他测试都失败了,因为我以不同的方式混合ES6和$ q promises.
最后,注意在控制器中我演示了两个FAILING测试确实在生产中起作用.
为什么Angular不让我在测试中混合ES6和$ q承诺,但在生产代码中没有问题?
我的单元测试也遇到了这个问题。在我得到对该问题的解释和正确的解决方案之前,我会使用解决方法:
if (window.Promise !== $q) {
window.Promise = $q;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
657 次 |
| 最近记录: |