I am new to AngularJS and run into some problems with unit testing. I have seen many examples of bullying calls to $ httpBackend, but when I do this it will not work unless I also enable $ rootScope. $ Apply ().
My service:
angular.module('myApp.services', ['ngResource'])
.factory('TestingService', ['$resource', function($resource) {
return $resource('/api/v1/values', {}, {
getValues: {
method: 'GET'
}
});
}]);
My unit test:
describe('Testing services', function() {
beforeEach(module('myApp.services'));
afterEach(function() {
inject(function($httpBackend) {
$httpBackend.verifyNoOutstandingExpectation();
$httpBackend.verifyNoOutstandingRequest();
});
});
describe('TestingService', function() {
it('would be nice to get an explanation for this',
inject(['$rootScope', '$httpBackend', 'TestingService',
function ($rootScope, $httpBackend, testingService) {
$httpBackend.expectGET('/api/v1/values').respond(100);
var result = testingService.getValues();
$httpBackend.flush();
expect(result).toBe(100);
alert(result);
}])
);
});
});
When Karma runs a test like this, I get:
Error: No pending request to flush !
Error: Unsatisfied requests: GET /api/v1/values
And if I include $ rootScope. $ apply (); I will get this (and the warning, of course, also gives the $ promise):
Expected { $promise : { then : Function, catch : Function, finally : Function }, $resolved : true } to be 100.
Can someone explain why I need "$ rootScope. $ Apply ();" skip waiting for a get? And why is the answer a promise instead of the false answer I indicated?