目前,我们正在尝试测试使用promise将值返回给控制器的角度服务。问题在于,我们附加到.then的函数不会在Jasmine中调用。
我们发现,在返回承诺后,在函数中添加$ rootScope.digest()可以调用同步承诺,但对于异步承诺仍然无效。
到目前为止的代码是
beforeEach(inject(function (Service, $rootScope)
{
service = Service;
root = $rootScope;
}));
it('gets all the available products', function (done)
{
service.getData().then(function (data)
{
expect(data).not.toBeNull();
expect(data.length).toBeGreaterThan(0);
done();
});
root.$digest();
});
在这种情况下,promise可以很好地调用,但是如果它是异步的,则不会被调用,因为在调用root。$ digest()时,promise还没有准备好进行“消化”。
有什么办法可以解决承诺后何时作出承诺,以便我可以致电摘要?还是可以自动执行的操作?谢谢 ;)
我们必须测试部分服务(已删除错误处理):
var app = angular.module('service', []);
/**
* Service for accessing data relating to the updates/downloads
* */
app.factory('Service', function ($q)
{
... init
function getData()
{
var deffered = $q.defer();
var processors = [displayNameProc];
downloads.getData(function (err, data)
{
chain.process(processors, data, function (err, processedData)
{
deffered.resolve(processedData);
});
});
return deffered.promise;
}
...
在问题是service.getData异步的情况下,可以解决诺言,但是由于已调用了root。$ digest,因此未调用测试代码中与该诺言关联的函数。希望这能提供更多信息
解决方法
var interval;
beforeEach(inject(function ($rootScope)
{
if(!interval)
{
interval = function ()
{
$rootScope.$digest();
};
window.setInterval(interval, /*timing*/);
}
}));
我最终使用上面的变通办法反复调用摘要,因此承诺的每一层都将有机会运行……它不是理想的或漂亮的,但是可以用于测试……
您应该将自己的主张移出,然后我相信:
beforeEach(inject(function (Service, $rootScope)
{
service = Service;
root = $rootScope;
}));
it('gets all the available products', function (done)
{
var result;
service.getData().then(function (data)
{
result = data;
done();
});
root.$digest();
expect(result ).not.toBeNull();
expect(result .length).toBeGreaterThan(0);
});
更新资料
为服务添加了$ timeout:
var app = angular.module('bad-service', []);
app.service('BadService', function ($q, $interval, $timeout)
{
this.innerPromise = function(){
var task = $q.defer();
console.log('Inside inner promise');
$timeout(function() {
console.log('Inner promise timer fired');
task.resolve();
}, 500);
// $interval(function(){
// }, 500, 1);
return task.promise;
}
});
我在断言之前刷新$ timeout:
beforeEach(module('test'));
describe('test', function(){
var service, root, $timeout;
beforeEach(inject(function (Service, $rootScope, _$timeout_)
{
$timeout = _$timeout_;
console.log('injecting');
service = Service;
root = $rootScope;
}));
/**
Test one
*/
it('Should work', function(done){
console.log('Before service call');
service.outerPromise().then(function resolve(){
console.log('I should be run!');
expect(true).toBeTruthy();
done();
});
// You will have to use the correct "resolve" here. For example when using:
// $httpbackend - $httpBackend.flush();
// $timeout- $timeout.flush();
$timeout.flush();
console.log('After service call');
});
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句