Darren Lamb Darren Lamb - 4 months ago 11
AngularJS Question

Injecting dependencies into Angular services for testing

I'm trying to do some test driven development of an angular service I'm writing using Jasmine. However, I seem to have stumbled at the first hurdle, and I cannot get my $resource dependency to resolve.

The error I get is
Unknown provider: $resourceProvider <- $resource <- lookupService

My code is as follows

Module:

(function() {
'use strict';

angular
.module('common', ['ngSanitize', 'ngAnimate']);
})();


Service:

(function() {
'use strict';

angular
.module('common')
.service('lookupService', lookupService);

lookupService.$inject = ['$resource', 'api'];

function lookupService($resource, api) {
return {
getLookup: getLookup
};

function getLookup() {
return "something";
}
}

})();


Test:

describe('Service tests',
function () {

var lookupService, mockApi, $httpBackend;

//mocks
beforeEach(function () {
mockApi = { getUri: jasmine.createSpy() };

angular.mock.module('common',
function ($provide) {
$provide.value('api', mockApi);
});
});


//injects
beforeEach(function () {
inject(function ($injector) {
$httpBackend = $injector.get('$httpBackend');
lookupService = $injector.get('lookupService');
});
});



//tests
it('should be able to return something',
inject(function () {
expect(lookupService.getLookup()).toEqual("something");
}));

});//Service tests


The angular-resource.js file is included in my runner file. I'm not sure where I'm going wrong, any help would be appreciated.

Thanks

Answer

ngResource must be a dependency:

(function() {
'use strict';

angular
    .module('common', ['ngSanitize', 'ngAnimate', 'ngResource']);
})();