我对 Karma 和 Jasmine 还很陌生,我用它们为我的 AngularJs 应用程序编写单元测试。
在运行测试套件函数时,默认情况下会调用我调用的用于初始化 Controller 中数据的测试套件函数。有什么方法可以在运行测试套件时避免此调用吗?
找到下面的代码片段:
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({});
关于javascript - Controller 方法在 AngularJs 中使用 Karma 调用 Jasmine 单元测试套件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34800203/