看起来promises
do not resolve in Angular/Jasmine tests unless you force a
$scope.$digest()
.这是愚蠢的IMO但很好,我有工作在适用(控制器)。
我现在的情况是我有一个服务,可以关心任何范围的应用程序,所有它从服务器返回一些数据,但promise似乎没有解决。
app.service('myService',function($q) { return { getSomething: function() { var deferred = $q.defer(); deferred.resolve('test'); return deferred.promise; } } });
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) { var promise = myService.getSomething(); promise.then(function(resp) { expect(resp).toBe('test'); expect(1).toEqual(2); done(); }); }); });
编辑:解决方案参考。显然,你被迫注入和消化$ rootScope,即使服务没有使用它。
it('should get something',function($rootScope,done) { var promise = myService.getSomething(); promise.then(function(resp) { expect(resp).toBe('test'); }); $rootScope.$digest(); done(); });
您需要在测试中注入$ rootScope并触发$ digest。
原文链接:https://www.f2er.com/angularjs/146152.html