gpt4 book ai didi

angularjs - 如何在 Karma/jasmine 中模拟 window.location 函数

转载 作者:行者123 更新时间:2023-12-03 15:15:32 24 4
gpt4 key购买 nike

我想模拟 Karma 中的一个功能,它在单击下载按钮后返回一个文件。
我有以下 AngularJS Controller :

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";
}
}

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

});

所以,我的想法是检查 scope.download 函数何时被调用,如果它返回正确的 url,即当我尝试 scope.download(1) 时,预期的答案将是 /secure/regulations/1/attachment , 大致。

我应该如何 mock 它?任何帮助表示赞赏!

最佳答案

使用 $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');
});

});

关于angularjs - 如何在 Karma/jasmine 中模拟 window.location 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30895929/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com