Here is an example of a service that utilizes $q.when
to wrap a promise from a third-party library:
// myService.js
angular.module('myApp', [])
.service('myService', function($q, $window) {
var api = new $window.MyAPI();
this.getData = function() {
return $q.when(api.fetchData());
};
});
Below is a unit test corresponding to the service:
describe('Testing async promises', function() {
beforeEach(module('myApp'));
var $rootScope, myService;
beforeEach(inject(function(_$rootScope_, myService) {
$rootScope = _$rootScope_;
myService = myService;
}));
it('should resolve the promise successfully', function(done) {
// This test should pass without any issues
myService.getData()
.then(function(data) {
expect(data).toBeDefined();
})
.finally(done);
$rootScope.$apply();
});
});
In the code above, calling myService.getData()
may or may not work depending on how $q
handles promises. Injecting the ng
module manually seems to make the spec work as expected:
describe('Resolving Q when tests', function() {
var myService;
beforeEach(function() {
var $injector = angular.injector(['ng', 'myApp']);
var myAPI = $injector.get('myService');
myService = myAPI.createInstance();
});
it('should successfully resolve the promise', function(done) {
myService.getData()
.then(function(data) {
expect(data).toBeDefined();
})
.finally(done);
});
});
Some questions to ponder include:
- Why does the first test fail to resolve?
- How does injecting the
ng
module affect the second test's success? - Is it necessary to use
$rootScope.$apply
in this context? - Is this pattern of wrapping promises with
$q.when
recommended?