简体   繁体   English

控制器方法使用AngularJs中的Karma调用Jasmine单元测试套件

[英]Controller methods call Jasmine unit test suite with Karma in AngularJs

I am pretty new to Karma and Jasmine which I am using to write unit tests for my AngularJs application. 对于Karma和Jasmine来说,我是一个新手,我正在为我的AngularJs应用程序编写单元测试。

While running the test suite functions which I have called to initialize data in my controller is getting called by default. 在运行测试套件函数时,默认情况下会调用我在控制器中初始化数据的函数。 Is there any way to avoid this call while running the test suite? 在运行测试套件时,有什么方法可以避免此调用?

Find the code snippet below: 在下面找到代码片段:

BaseCtrl.js

App.controller('BaseCtrl', ['$scope', '$rootScope', 'Data', function($scope, $rootScope, Data){
    //initialize
    $rootScope.loader = false;
    $rootScope.data = false;

    $scope.init = function(){
        $rootScope.loader = true;
        Data.init(function(data){
            $rootScope.loader = false;
            $rootScope.data = data;
        });   
    };

    $scope.init();
}])

Data.js

App.service('Data', ['$http', function($http){
    return {
        init:function(callback){
            $http.get('/url').success(function(response){
               callback(response);
            });
        }
    };
}]);

BaseCtrl.spec.js

describe('BaseCtrl', function(){
    beforeEach(module('app'));

    var $controller, $rootScope, $scope;

    beforeEach(inject(function(_$controller_, _$rootScope_){
        $controller = _$controller_;
        $rootScope = _$rootScope_.$new();
    }));

    describe('Loader', function(){
        var controller, $scope = {};
        beforeEach(function(){
            controller = $controller('BaseCtrl', {$scope:$scope, $rootScope:$rootScope});
        });

        it('should be false by default', function(){

            // Check the default value
            expect($rootScope.loader).toBe(false);

            // Some code to determine the call, then

            expect($rootScope.loader).toBe(true);

            // Some code to determine the call is done, then

            expect($rootScope.loader).toBe(false);
        });
    });
});

是的,使用$httpBackend创建一个模拟并返回您想要的任何内容。

$httpBackend.when('GET', '/url').respond({});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM