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

Controller methods call Jasmine unit test suite with Karma in AngularJs

本文关键字:调用 Karma Jasmine 单元测试 套件 方法 AngularJs 控制器      更新时间:2023-09-26

我对Karma和Jasmine很陌生,我用它来为我的AngularJs应用程序编写单元测试。

在运行测试套件时,默认情况下会调用我为初始化控制器中的数据而调用的函数。在运行测试套件时,有什么方法可以避免此调用?

在下面找到代码片段:

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