Does anyone have an example of how to unit test a provider?
For example:
config.js
an
i've been using @Mark Gemmill's solution and it works well, but then stumbled across this slightly less verbose solution which removes the need for a fake module.
https://stackoverflow.com/a/15828369/1798234
So,
var provider;
beforeEach(module('app.config', function(theConfigProvider) {
provider = theConfigProvider;
}))
it('tests the providers internal function', inject(function() {
provider.mode('local')
expect(provider.$get().mode).toBe('local');
}));
If your providers $get method has dependencies, you can either pass them in manually,
var provider;
beforeEach(module('app.config', function(theConfigProvider) {
provider = theConfigProvider;
}))
it('tests the providers internal function', inject(function(dependency1, dependency2) {
provider.mode('local')
expect(provider.$get(dependency1, dependency2).mode).toBe('local');
}));
Or use the $injector to create a new instance,
var provider;
beforeEach(module('app.config', function(theConfigProvider) {
provider = theConfigProvider;
}))
it('tests the providers internal function', inject(function($injector) {
provider.mode('local')
var service = $injector.invoke(provider);
expect(service.mode).toBe('local');
}));
Both of the above would also allow you to reconfigure the provider for each individual it
statement in a describe
block. But if you only need to configure the provider once for multiple tests, you can do this,
var service;
beforeEach(module('app.config', function(theConfigProvider) {
var provider = theConfigProvider;
provider.mode('local');
}))
beforeEach(inject(function(theConfig){
service = theConfig;
}));
it('tests the providers internal function', function() {
expect(service.mode).toBe('local');
});
it('tests something else on service', function() {
...
});