Question

I would like to know, when testing my controller, if a sessionStorage variable is set after calling a function. Here is my test :

it('should be able to set language to the storage through SessionService', inject(['SessionService', function (SessionService) {
        $scope.openChooseLanguage();
        $scope.modalInstance.close('fr');
        // What to write there ?
 }]));

In my controller I have the openChooseLanguage function that set a 'lang' item and the returned value as the second parameter in my SessionService :

$scope.openChooseLanguage = function(){
    if($scope.lang == '' || $scope.lang == null){
        $scope.modalInstance = $modal.open({
            templateUrl: 'views/modals/chooseLanguage.html',
            controller: 'ChooseLanguageCtrl'
        });

        $scope.modalInstance.result.then(function (result) {
            //Define user language in Session Storage
            SessionService.set('lang', result);
        }, function () {
            $scope.canceled = true;
            $scope.openChooseLanguage();
        });
    }
};

And here is my SessionService that simply set, get, unset, my items :

return {
        get : function(key){
            return sessionStorage.getItem(key);
        },
        set : function(key, val){
            broadcast(key, val);
            return sessionStorage.setItem(key, val);
        },
        unset : function(key){
            return sessionStorage.removeItem(key);
        }
    };

So what is the solution to know if the 'lang' item has been set? I am just starting unit testing with AngularJS and Jasmine so I am a little confused for now...

UPDATE

I just tried to add this to my test :

beforeEach(function() {
        $sessionStorage = jasmine.createSpyObj('SessionService', ['get', 'set', 'unset']);
    });

it('should be able to set language to the storage through SessionService', inject(['SessionService', function (SessionService) {
        $scope.openChooseLanguage();
        $scope.modalInstance.close('fr');
        expect($sessionStorage.set).toHaveBeenCalledWith('lang','fr');
    }]));

But when running my tests I have the following error :

Expected spy SessionService.set to have been called with [ 'lang', 'fr' ] but it was never called

Was it helpful?

Solution

Do the following:

  1. Declare variable which will hold the injected SessionService
  2. Inject the service and use spyOn on its set method
  3. Use toHaveBeenCalledWith method to check

As a result, you should have this:

var SessionService;

beforeEach(inject(function(_SessionService_) {
     SessionService = _SessionService_;   
     spyOn(SessionService,'set').andCallThrough();
}));

it('should be able to set language to the storage through SessionService',function(){
     $scope.openChooseLanguage();
     $scope.modalInstance.close('fr');

     expect(SessionService.set).toHaveBeenCalledWith('lang','fr');
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top