Hug*_*ako 14 unit-testing angularjs karma-jasmine
我想在Karma中模拟一个功能,它在点击下载按钮后返回一个文件.我有以下AngularJS控制器:
var secure = angular.module('secure', []);
secure.controller('ProcedureController', ProcedureController);
ProcedureController.$inject = ['$controller', '$rootScope', '$scope', '$http'];
function ProcedureController($controller, $rootScope, $scope, $http) {
... // Controller does more stuff
var href = window.location.href.split('/');
var baseUrl = href[0] + '//' + href[2];
var url = baseUrl + "/secure/regulations";
$http.get(url)
.success(function (data) {
$scope.questions = data[0];
})
$scope.download = function (msg) {
window.location = url + "/" + msg + "/attachment";
}
}
Run Code Online (Sandbox Code Playgroud)
window.location对象只调用一个RESTful服务,直接为他提供所需的文件.这基本上就是我的尝试测试:
describe('ProcedureController', function () {
beforeEach(module('secure'));
beforeEach(inject(function ($rootScope, $http, $controller, $injector) {
scope = $rootScope.$new();
ProcedureController = $controller('ProcedureController', {
$scope: scope,
$http: $http
});
}));
it ('should download something', function() {
expect(scope.download(1)).toBeDefined();
});
});
Run Code Online (Sandbox Code Playgroud)
所以,我的想法是检查scope.download函数何时被调用,如果它返回正确的url,即,当我尝试scope.download(1)时,预期的答案将是/ secure/regulations/1/attachment,粗略.
我该怎么嘲笑它?任何帮助表示赞赏!
Waw*_*awy 14
使用$ window代替:
var secure = angular.module('secure', []);
secure.controller('ProcedureController', ProcedureController);
ProcedureController.$inject = ['$controller', '$rootScope', '$scope', '$http', '$window'];
function ProcedureController($controller, $rootScope, $scope, $http, $window) {
... // Controller does more stuff
var href = $window.location.href.split('/');
var baseUrl = href[0] + '//' + href[2];
var url = baseUrl + "/secure/regulations";
$http.get(url)
.success(function (data) {
$scope.questions = data[0];
})
$scope.download = function (msg) {
$window.location = url + "/" + msg + "/attachment";
}
}
describe('ProcedureController', function () {
var windowObj = {location: {href: ''}};
beforeEach(mock.module(function($provide) {
$provide.value('$window', windowObj);
}));
beforeEach(module('secure'));
beforeEach(inject(function ($rootScope, $http, $controller, $injector) {
scope = $rootScope.$new();
ProcedureController = $controller('ProcedureController', {
$scope: scope,
$http: $http
});
}));
it ('should download something', function() {
expect(scope.download).toBeDefined();
scope.download(1);
expect(windowObj.location.href).toEqual('/secure/regulations/1/attachment');
});
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
19444 次 |
| 最近记录: |