Karma错误 - 预期未定义要定义

时间:2016-05-30 13:25:52

标签: javascript angularjs karma-runner karma-jasmine spyon

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

我尝试使用localStorageService模仿spyOn为真,以满足条件,但这仍然无济于事。任何解决方案对我的启动都有很大的帮助。

控制器:

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


});

1 个答案:

答案 0 :(得分:1)

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