I've got an AngularJS service that, onload, fires one of its own methods. This method refers to another service's property.
var app = angular.module('myApp');
app.service('myService',["anotherService", function(anotherService) {
var self = {
bar: 0,
foo: function() {
self.bar += anotherService.someProperty;
}
};
self.foo();
}]);
So, as you can see, I've injected anotherService into myService and consumed a property of anotherService under the foo() method. Notice at the end of the service self.foo() is fired so when the application loads, so does the foo() method.
If I comment out self.foo() all of my tests work just fine. Otherwise, they all fail:
TypeError: undefined is not an object (evaluating 'anotherService.someProperty')
The peculiar thing to me is that tests I've created for controllers that don't even inject myService will fail unless this is commented out.
So, a few questions now that you hopefully understand this portion of my application:
- Why would this error occur when testing controllers that don't inject myService?
- I've tried mocking the service in controllers (even if they don't inject the service) to set anotherService.someProperty to no avail.
- I'm not sure whether I should mock it as an extension of a mocked myService or if I should mock both myService and anotherService in the controller for it to work properly. It seems each described test is namespaced so creating a test for myService wouldn't affect tests for other controllers, services, etc. However, and I've already said this, controllers that don't inject this service still fail because of the above error.
- I tried describing a test for myService to attempt mocking the data, but it didn't seem to change anything:
describe("Test myService", function() {
beforeEach(inject(function (_myService_, _anotherService_) {
myService = _myService_;
anotherService = _anotherService_;
sessionService.someProperty = 1;
}));
it("self.bar should equal 1", function() {
expect(sessionService.bar).toEqual(1);
});
});
So, for now, I'm getting by through commenting out the self.foo() line of myService in order for my other unit tests to run.