2

我想对我的控制器进行单元测试。我从expect API 的基本测试断言开始。但是我在条件检查中模拟范围方法时面临挑战。我收到一个undefined错误,因为它在范围内不可用,只有全局logout()方法可用。

我尝试将localStorageServiceusing模拟spyOn为 true 以满足条件,但这仍然无济于事。任何解决方案都会对我启动有很大帮助。

控制器:

angular.module('app').controller('sampleCtrl',

        function($scope, $state, $http, $rootScope, localStorageService) {

            if (!(localStorageService.get('isAuthenticated'))) {

                 $state.go('home');

            }
            if (localStorageService.get('isAuthenticated') === true) {

                 //http post calls made here to perform certain operation on page load

                 $scope.someMethod = function(){

                     //do something

                  }

            }

            $scope.logOut = function() {

               localStorageService.set('property', '');

               localStorageService.set('isAuthenticated', false);

               $state.go('home');

          };
 });

业力:

'use strict';

describe('Controller: sampleCtrl', function() {

    /** to load the controller's module */
    beforeEach(module('app'));

    var sampleCtrl,scope,httpBackend,deferred,rootScope;

    beforeEach(inject(function ($controller,_$rootScope_,$httpBackend,$q) {

        var store = {};
        scope= _$rootScope_.$new(); // creates a new child scope of $rootScope for each test case
        rootScope           = _$rootScope_;
        localStorageService = _localStorageService_;
        httpBackend         = $httpBackend;

        httpBackend.whenGET(/\.html$/).respond(''); 

        spyOn(localStorageService, 'set').and.callFake(function (key,val) {
            store[key]=val;
         });

        spyOn(localStorageService, 'get').and.callFake(function(key) {
            return store[key];
         });

        sampleCtrl = $controller('sampleCtrl',{
            _$rootScope_:rootScope,
             $scope:scope,
             $httpBackend:httpBackend,
            _localStorageService_:localStorageService
            // add mocks here
        });

        localStorageService.set('isAuthenticated',true);

    }));

    /**ensures $httpBackend doesn’t have any outstanding expectations or requests after each test*/
    afterEach(function() {
        httpBackend.verifyNoOutstandingExpectation(); 
        httpBackend.verifyNoOutstandingRequest();     
    }); 


    it('sampleCtrl to be defined:',function(){

        httpBackend.flush(); 
        expect(sampleCtrl).toBeDefined();

    });

    // failing test case - scope.someMethod not available in scope
    it('is to ensure only authenticated user can access the state methods',function(){
            localStorageService.get('isAuthenticated');
            httpBackend.flush();
            expect(scope.someMethod).toBeDefined(); 
    });


});
4

1 回答 1

1

我已经设法让它工作了。问题是 localStorageService在启动控制器时没有将isAuthenticated设置为 true。在调用控制器之前将其设置为true 。

于 2016-05-31T08:33:20.567 回答