Does anyone have an example of how to unit test a provider?
For example:
config.js
an
@Stephane Catala's answer was particularly helpful, and I used his providerGetter to get exactly what I wanted. Being able to get the provider to do initialization and then the actual service to validate that things are working correctly with various settings was important. Example code:
angular
.module('test', [])
.provider('info', info);
function info() {
var nfo = 'nothing';
this.setInfo = function setInfo(s) { nfo = s; };
this.$get = Info;
function Info() {
return { getInfo: function() {return nfo;} };
}
}
The Jasmine test spec:
describe("provider test", function() {
var infoProvider, info;
function providerGetter(moduleName, providerName) {
var provider;
module(moduleName,
[providerName, function(Provider) { provider = Provider; }]);
return function() { inject(); return provider; }; // inject calls the above
}
beforeEach(function() {
infoProvider = providerGetter('test', 'infoProvider')();
});
it('should return nothing if not set', function() {
inject(function(_info_) { info = _info_; });
expect(info.getInfo()).toEqual('nothing');
});
it('should return the info that was set', function() {
infoProvider.setInfo('something');
inject(function(_info_) { info = _info_; });
expect(info.getInfo()).toEqual('something');
});
});