How to mock $window.location.replace in AngularJS unit test?

szimek picture szimek · Nov 27, 2013 · Viewed 33.4k times · Source

I've got the following service:

angular.module("services")
.factory("whatever", function($window) {
  return {
    redirect: function() {
      $window.location.replace("http://www.whatever.com");
    }
  };
});

How to mock $window object in unit test to prevent reloading the page when running tests?

I tried using

spyOn($window.location, 'replace').andReturn(true);

, but it didn't work (still got "Some of your tests did a full page reload!" error) and

$provide.value('$window', {location: {replace: jasmine.createSpy()}})

, but I was getting an error (Error: [ng:areq] Argument 'fn' is not a function, got Object) with stack trace pointing only to angular own source, so it wasn't very helpful...

Answer

LostInComputer picture LostInComputer · Jan 2, 2014

In Chrome (didn't test inother browsers), location.replace is readonly so spyOn wasn't able to replace it.

$provide.value should work. Something must be wrong somewhere in your code.

Here is a working unit test

describe('whatever', function() {
    var $window, whatever;

    beforeEach(module('services'));

    beforeEach(function() {
      $window = {location: { replace: jasmine.createSpy()} };

      module(function($provide) {
        $provide.value('$window', $window);
      });

      inject(function($injector) {
        whatever = $injector.get('whatever');
      });
    });

    it('replace redirects to http://www.whatever.com', function() {
      whatever.redirect();
      expect($window.location.replace).toHaveBeenCalledWith('http://www.whatever.com');
    });
});