Reputation: 685
Let's says we have the following angular controller :
.controller('Ctrl', function ($scope, localStorageService) {
$scope.vma = localStorageService.get('vma_vma') || 10;
}
It uses an external service (localStorageService) during initialization. Basicelly localStorageService.get returns a previously stored value of 'vma_vma' or null if not present.
I've made a mock of localStorageService and the unit test looks like this:
describe('Controller: Ctrl', function () {
// load the controller's module
beforeEach(module('App', function($provide){
localStorage = {};
localStorage.get = jasmine.createSpy();
localStorage.set = jasmine.createSpy();
$provide.value('localStorageService', localStorage);
}));
var Ctrl,
scope;
// Initialize the controller and a mock scope
beforeEach(inject(function ($controller, $rootScope) {
scope = $rootScope.$new();
Ctrl = $controller(' Ctrl', {
$scope: scope,
localStorageService: localStorageService
});
}));
I'd like to be able to test 2 cases:
it('should get vma and return 10 when vma not present', function () {
???
expect($scope.vma).toBe(10);
});
it('should get vma in localstorage when present', function () {
???
expect($scope.vma).toBe(15);
});
});
Thank you for your help.
Upvotes: 0
Views: 463
Reputation: 691963
You don't need to create a mock localStorageService. Just to spy on the real one. But the solution is finally identical: just configure the mock/spy to return what you want before instantiating the controller:
describe('Controller: Ctrl', function () {
var $controller,
localStorageService,
scope;
beforeEach(module('App'));
beforeEach(inject(function(_$controller_, $rootScope, _localStorageService_) {
scope = $rootScope.$new();
$controller = _$controller_;
localStorageService = _localStorageService_;
}));
it('should get vma and return 10 when vma not present', function() {
// given no vma_vma in the local storage
spyOn(localStorageService, 'get').and.returnValue(null);
// when instantiating the controller
$controller('Ctrl', {$scope: scope});
// then its vma is initialized to 10
expect($scope.vma).toBe(10);
expect(localStorageService).toHaveBeenCalledWith('vma_vma');
});
it('should get vma in localstorage when present', function() {
// given a vma_vma equal to 15 in local storage
spyOn(localStorageService, 'get').and.returnValue(15);
// when instantiating the controller
$controller('Ctrl', {$scope: scope});
// then its vma is initialized to 15
expect($scope.vma).toBe(15);
expect(localStorageService).toHaveBeenCalledWith('vma_vma');
});
});
Upvotes: 1