angularjs - How do I resolve a $q.when promise in unit tests? -
i'm using $q.when
convert third-party promises (those returned pouchdb) angular promises.
given:
'use strict'; angular.module('test', []) .service('pouchdb', function($q, $window) { var db = new $window.pouchdb('test'); this.info = function() { homecoming $q.when(db.info.apply(db, arguments)); }; }) .controller('test', function($scope, pouchdb) { pouchdb.info() .then(function(info) { $scope.result = info; }) .catch(function(error) { $scope.result = error; }); });
… in browser, info
returned , $scope
updated correctly. however, given next unit test (jasmine 2.x):
describe('q when tests', function() { beforeeach(module('test')); var $rootscope, pouchdb; beforeeach(inject(function(_$rootscope_, pouchdb) { $rootscope = _$rootscope_; pouchdb = pouchdb; })); it('should resolve promise', function(done) { pouchdb.info() .then(function(info) { expect(info).tobedefined(); }) .finally(done); $rootscope.$apply(); }); });
… info
never resolved , jasmine (via karma & phantomjs) throws:
error: timeout - async callback not invoked within timeout specified jasmine.default_timeout_interval.
by calling $rootscope.$apply()
, i'd expect digest triggered , promise resolved. how resolve promise in case?
note, i've loaded es5-shim
bind
/apply
back upwards in phantomjs.
edit: i've tried moving $rootscope.$apply()
top of test (and in aftereach
block), alternating $rootscope.$digest()
, increasing jasmine's timeout (jasmine.default_timeout_interval = 10000;
).
unwittingly, resolved issue manually injecting ng
:
describe('working q when tests', function() { var pouchdb; beforeeach(function() { var $injector = angular.injector(['ng', 'test']); var pouchdb = $injector.get('pouchdb'); pouchdb = pouchdb('db'); }); it('should resolve promise', function(done) { pouchdb.info() .then(function(info) { expect(info).tobedefined(); }) .finally(done); }); });
angularjs unit-testing promise
No comments:
Post a Comment