balteo balteo - 1 year ago 99
AngularJS Question

Unit testing the AngularJS $window service

I would like to unit test the following AngularJs service:

.factory('httpResponseInterceptor', ['$q', '$location', '$window', 'CONTEXT_PATH', function($q, $location, $window, contextPath){
return {
response : function (response) {
//Will only be called for HTTP up to 300
return response;
responseError: function (rejection) {
if(rejection.status === 405 || rejection.status === 401) {
$window.location.href = contextPath + '/signin';
return $q.reject(rejection);

I have tried with the following suite:

describe('Controllers', function () {
var $scope, ctrl;
beforeEach(module(function($provide) {
$provide.constant('CONTEXT_PATH', 'bignibou'); // override contextPath here
describe('CreateCurriculumCtrl', function () {
var mockBackend, location, _window;
beforeEach(inject(function ($rootScope, $controller, $httpBackend, $location, $window) {
mockBackend = $httpBackend;
location = $location;
_window = $window;
$scope = $rootScope.$new();
ctrl = $controller('CreateCurriculumCtrl', {
$scope: $scope

it('should redirect to /signin if 401 or 405', function () {
mockBackend.whenPOST('bignibou/curriculum/new').respond(function(method, url, data, headers){
return [401];


However, it fails with the following error message:

PhantomJS 1.9.2 (Linux) Controllers CreateCurriculumCtrl should redirect to /signin if 401 or 405 FAILED
Expected 'http://localhost:9876/context.html' to equal '/bignibou/signin'.
PhantomJS 1.9.2 (Linux) ERROR
Some of your tests did a full page reload!

I am not sure what is going wrong and why. Can anyone please help?

I just want to ensure the
is equal to

edit 1:

I managed to get it to work as follows (thanks to "dskh"):

beforeEach(module('config', function($provide){
$provide.value('$window', {location:{href:'dummy'}});

Answer Source

You can inject mock dependencies when you load in your module:

angular.mock.module('curriculumModule', function($provide){
            $provide.value('$window', {location:{href:'dummy'}});
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download