我已经阅读过这方面的几个主题,但无法找到问题的解决方案。在我的控制器中,我有一个功能:
this.dName = function() {
var url = $location.absUrl();
var matches = url.match(/\/dName\/(.*)$/);
return matches[1];
};
这导致我的测试失败,因为没有绝对的URL可以抓取。我将如何模仿$location.absUrl
以便我的测试可以通过?
答案 0 :(得分:1)
例如,你可以窥探$location
服务,茉莉花就是:
describe('MyController', function(){
beforeEach(module('myApp'));
var MyController, scope, $location;
beforeEach(inject(function($injector) {
var $controller = $injector.get('$controller');
var $rootScope = $injector.get('$rootScope');
$location = $injector.get('$location');
scope = $rootScope.$new();
MyController = $controller('MyController', {
$scope: scope,
});
}));
it('Check dName', function () {
spyOn($location, 'absUrl').and.returnValue(["match0", "match1"]);
var match = scope.dName();
expect(match).toEqual("match1");
expect($location.absUrl).toHaveBeenCalled();
});
});