Mocking $location
Answer to SO question
HTML
<script src="http://pivotal.github.io/jasmine/lib/jasmine-1.3.1/jasmine.js"></script>
<script src="http://pivotal.github.io/jasmine/lib/jasmine-1.3.1/jasmine-html.js"></script>
<link rel="stylesheet" href="http://pivotal.github.io/jasmine/lib/jasmine-1.3.1/jasmine.css">
<script src="http://code.angularjs.org/1.0.5/angular.js"></script>
<script src="http://code.angularjs.org/1.1.4/angular-mocks.js"></script>
JavaScript
//--- CODE --------------------------
angular.module('myapp.test', [], function () {
}).controller('testcont', function($scope, $location) {
$scope.a = 10;
$scope.path = $location.path();
});
// --- SPECS -------------------------
describe('controllers', function(){
var scope;
beforeEach(angular.mock.module('myapp.test'));
beforeEach(inject(function($controller, $rootScope, $location){
scope = $rootScope.$new();
spyOn($location, 'path').andReturn('Fake location');
$controller('testcont', {$scope:scope});
}));
it('should initialize scope', function(){
expect(scope.a).toBe(10)
});
it('should spy on $location', function($location){
expect(scope.path).toBe('Fake location');
});
});
// --- Runner -------------------------
(function () {
var jasmineEnv = jasmine.getEnv();
jasmineEnv.updateInterval = 1000;
var htmlReporter = new jasmine.HtmlReporter();
jasmineEnv.addReporter(htmlReporter);
jasmineEnv.specFilter = function (spec) {
return htmlReporter.specFilter(spec);
};
var currentWindowOnload = window.onload;
window.onload = function () {
if (currentWindowOnload) {
currentWindowOnload();
}
execJasmine();
};
function execJasmine() {
jasmineEnv.execute();
}
})();