2016-04-08 7 views
0

のは、我々は次のような角度のコントローラを持っていると言いましょう:

.controller('Ctrl', function ($scope, localStorageService) { 
    $scope.vma = localStorageService.get('vma_vma') || 10; 
} 

それは初期化時に、外部サービス(localStorageService)を使用しています。 Basicelly localStorageService.getは、以前に格納された 'vma_vma'の値を返します。存在しない場合はnullを返します。

私はlocalStorageServiceのモックを作ったし、ユニットテストは、次のようになります。

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

私は2例をテストできるようにしたいと思います:

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

はあなたをありがとう助けて。

答えて

1

モックlocalStorageServiceを作成する必要はありません。本当のものをスパイするだけです。しかし、解決策は最終的には同じです:ちょうどの前にがコントローラをインスタンス化する前に返すようにモック/スパイを設定してください:

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'); 
    }); 
}); 
関連する問題