After several hours of searching and experimenting, my mind is blown. A straight-forward and working example of how to unit-test an AngularJS provider is nowhere to be found and I cannot get it to work myself, no matter how hard I try.
In the below example, the service is properly injected and working. The provider is not injected and cannot be configured, because it never arrives in the code-block where configuration should be possible.
Is there anyone that can provide a working 'How to unit-test an AngularJS provider' example ?
angular.module('app',[]);
angular.module('app').service('testBasicService', function () {
return {
serviceMethod: function () {
alert("serviceMethod");
}
};
});
angular.module('app').provider('testAdvancedService', function () {
this.$get = function () {
this.providerMethod = function () {
alert("providerMethod");
}
}
});
describe("Test", function () {
beforeEach(module("app"), function (testAdvancedServiceProvider) {
// code never arrives here
});
it("should just work", inject(function (testBasicService, testAdvancedService) {
testBasicService.serviceMethod();
testAdvancedService.providerMethod(); // testAdvancedService is undefined here
}));
});
I think the reason why testAdvancedService is undefined in your test is because the $get method in the provider doesn't have a return value. If it did return an object, that object would be the testAdvancedService injected in your test.
If you have a function defined in your provider that you want to test, I found that this works:
describe("Test", function () {
beforeEach(module("app"));
var provider;
beforeEach(function () {
module(function ($provide, testAdvancedServiceProvider) {
provider = $provide.provider('testAdvancedServiceProvider', testAdvancedServiceProvider);
});
});
it("should just work", inject(function (testBasicService, testAdvancedService) {
testBasicService.serviceMethod();
alert(testAdvancedService); // result of the $get function. undefined as it is now.
provider.providerMethod();
}));
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.