The test in this code does not succeed. I can't seem to successfully test the return of an asynchronous function.
describe('mocking services', function () {
var someService, deferred;
beforeEach(function () {
module(function($provide){
$provide.factory('someService', function($q){
return{
trySynch: function(){
return 33;
},
tryAsynch: function(){
deferred = $q.defer();
return deferred.promise;
}
};
});
});
inject(function (_someService_) {
someService = _someService_;
});
});
it('should be able to test values from both functions', function () {
expect(someService.trySynch()).toEqual(33);
var retVal;
someService.tryAsynch().then(function(r){
retVal = r;
});
deferred.resolve(44);
expect(retVal).toEqual(44);
});
});
When I run it I get the following error:
Chrome 36.0.1985 (Mac OS X 10.9.4) mocking services should be able to test values from both functions FAILED
Expected undefined to equal 44.
Error: Expected undefined to equal 44.
at null.<anonymous> (/Users/selah/WebstormProjects/macrosim-angular/test/spec/services/usersAndRoles-service-test.js:34:24)
How can I make this test pass?
When mocking async calls with $q, you need to use $rootScope.$apply() because of how $q is implemented.
Specifically, the .then method does not get called synchronously, it is designed to always be async, regardless of how it was called - sync or async.
To achieve that, $q is integrated with $rootScope. Therefore, in your unit tests, you need to notify the $rootScope that something was changed (ie - trigger a digest cycle). To do that, you call $rootScope.$apply()
See here (specifically the "Differences between Kris Kowal's Q and $q section")
Working code looks like this:
describe('mocking services', function () {
var someService, deferred, rootScope;
beforeEach(function () {
module(function($provide){
$provide.factory('someService', function($q){
return{
trySynch: function(){
return 33;
},
tryAsynch: function(){
deferred = $q.defer();
return deferred.promise;
}
};
});
});
inject(function ($injector) {
someService = $injector.get('someService');
rootScope = $injector.get('$rootScope');
});
});
it('should be able to test values from both functions', function () {
expect(someService.trySynch()).toEqual(33);
var retVal;
someService.tryAsynch().then(function(r){
retVal = r;
});
deferred.resolve(44);
rootScope.$apply();
expect(retVal).toEqual(44);
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With