似乎承诺不会在Angular/Jasmine测试中解决,除非你强迫一个$scope.$digest().这是愚蠢的IMO,但很好,我有适用的工作(控制器).
我现在是这种情况是我有一个并不十分关心应用程序中的任何一个范围的服务,它的作用是从服务器返回的一些数据,但承诺似乎并没有被解决.
app.service('myService', function($q) {
return {
getSomething: function() {
var deferred = $q.defer();
deferred.resolve('test');
return deferred.promise;
}
}
});
Run Code Online (Sandbox Code Playgroud)
describe('Method: getSomething', function() {
// In this case the expect()s are never executed
it('should get something', function(done) {
var promise = myService.getSomething();
promise.then(function(resp) {
expect(resp).toBe('test');
expect(1).toEqual(2);
});
done();
});
// This throws an error because done() is never called.
// Error: Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.
it('should get something', function(done) …Run Code Online (Sandbox Code Playgroud) 我使用$ q.when来包装其他lib promises.它就像一个魅力,但是当我尝试在Karma中运行它时,即使我运行$ digest甚至超时后,promise仍然会解决(done()永远不会被执行).这是示例代码:
describe('PouchDB', function () {
var $q, $rootScope;
beforeEach(inject(function (_$rootScope_, _$q_) {
$rootScope = _$rootScope_;
$q = _$q_;
}));
it("should run", function (done) {
function getPromise() {
var deferred = Q.defer();
deferred.resolve(1);
return deferred.promise;
}
$q.when(getPromise())
.then(function () {
done(); // this never runs
});
$rootScope.$digest();
});
Run Code Online (Sandbox Code Playgroud)
为什么?这是什么原因?我真的无法得到它.
更新(解决方法)
我不明白为什么$ q.when在Karma中没有得到解决 - 它有nextTick功能,但我无法调试问题.相反,我放弃了$ q.when并编写了简单的函数,将PouchDB(或任何其他类似的Q)转换为$ q:
.factory('$utils', function ($q, $rootScope) {
return {
to$q: function (promise) {
var deferred = $q.defer();
promise.then(function …Run Code Online (Sandbox Code Playgroud) 在Angular中使用$ q时,有一个关于同步嵌套promise的问题.以下代码是否会确保等待整个承诺链?意味着在$ q.all块中等待返回promises的服务的嵌套调用?
var call1 = service1.get('/someUr').then(function(){
return service2.get('/someUrl2'); //returns promise
});
var call2 = service3.get('/someUr').then(function(){
return 'hello';
});
var call3 = service4.get('/someUr').then(function(){
return service3.get('/someUrl3');//returns promise
});
$q.all(call1,call2,call3).then(function(){
console.log('All asynch operations are now completed');
});
Run Code Online (Sandbox Code Playgroud)
基本上:当前代码是否有可能在解决所有嵌套的promise之前执行$ q.all的then?还是递归?