在AngularJS的单元测试中获取sessionStorage项

时间:2014-04-25 06:56:36

标签: angularjs unit-testing jasmine karma-runner

我想知道,在测试我的控制器时,如果在调用函数后设置了sessionStorage变量。这是我的测试:

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 ?
 }]));

在我的控制器中,我有openChooseLanguage函数,它将一个'lang'项和返回值设置为我的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();
        });
    }
};

这是我的SessionService,只需设置,获取,取消设置我的项目:

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);
        }
    };

那么知道'lang'项目是否已设置的解决方案是什么?我刚刚开始使用AngularJS和Jasmine进行单元测试,所以我现在有点困惑......

更新

我只是想把它添加到我的测试中:

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');
    }]));

但是在运行测试时我遇到以下错误:

  

使用['lang'调用的预期间谍SessionService.set,   'fr']但它从未被称为

1 个答案:

答案 0 :(得分:2)

执行以下操作:

  1. 声明将保留注入的SessionService
  2. 的变量
  3. 注入服务并在其spyOn方法
  4. 上使用set
  5. 使用toHaveBeenCalledWith方法检查
  6. 因此,您应该拥有:

    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');
    });