我想对控制器进行单元测试。我从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();
    });


});

最佳答案

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

关于javascript - karma 报错-预期未定义,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37526865/

10-11 08:13