I have an AngularJS service that loads data from localStorage while "initializing" (i.e. in the factory function), like this:
module.service('myService', function ($localStorage) {
var data = $localStorage.data;
if (!isValid(data)) // isValid omitted on purpose, not relevant.
data = undefined;
return {
getData: function() {
return data;
}
setData: function(value) {
if (isValid(value))
data = value;
}
};
}
In my tests, I'd like to check that data
is actually loaded from localStorage if the value is present there and valid; this is not about testing isValid, but the service initialization that uses it and $localStorage.
I'd like to be able to call the myService factory inside my test. I'm getting an initialized instance of it in the beforeEach hook since I need to test methods of myService as well. I think I need to have a different instance created for my specific initialization test, but since services are singletons in AngularJS, I'm not sure whether this can be done.
describe('myService', function() {
myService = $localStorage = null;
beforeEach(module('app'));
beforeEach(inject(function($injector) {
myService = $injector.get('myService');
$localStorage = $injector.get('$localStorage');
});
it('should look for stuff in localStorage on creation', function () {
$localStorage.data = 'my data';
// I'd like to call service factory here!!
myService.getData().should.equal('my data');
});
});
Can this be achieved? Does my code have a difficult-to-test structure, or am I disrespecting the "Angular way" and this should be done differently?
Try this:
describe('myService', function() {
myService = $localStorage = null;
beforeEach(module('app'));
beforeEach(inject(function($injector) {
$localStorage = $injector.get('$localStorage');
$localStorage.data = 'my data';
myService = $injector.get('myService');
});
it('should look for stuff in localStorage on creation', function () {
myService.getData().should.equal('my data');
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With